blob: f1b2d35cab7503235f83d0b9dee775817fb75191 [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
Patrik Gustavsson3a269202021-01-21 08:28:55 +010031from .errors import VelaError
Dwight Lidman42fed942020-05-29 09:37:03 +020032from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Louis Verhaard8912c532020-09-30 12:11:49 +020033from .numeric_util import clamp_sigmoid
Louis Verhaarde0ef2732020-06-03 08:56:44 +020034from .numeric_util import full_shape
Louis Verhaardf03bad32020-09-25 08:30:44 +020035from .numeric_util import round_away_zero
Louis Verhaarde8a5a782020-11-02 18:04:27 +010036from .operation import create_activation_function
Diego Russoe8a10452020-04-21 17:39:10 +010037from .operation import NpuBlockType
Louis Verhaardaee5d752020-09-30 09:01:52 +020038from .operation import Op
Diego Russoe8a10452020-04-21 17:39:10 +010039from .operation import Operation
Michael McGeagh16895482020-12-14 15:51:20 +000040from .operation import Padding
Fredrik Svedbergd9c2c422020-12-01 16:33:45 +010041from .operation_util import create_avgpool_nop
patrik.gustavssoneeb85152020-12-21 17:10:40 +000042from .shape4d import Shape4D
Fredrik Svedberga0c36242020-06-03 15:43:31 +020043from .softmax import SoftMax
Tim Hall93582962020-09-09 21:58:15 +010044from .tensor import check_quantized_tens_scaling_equal
Michael McGeaghc5b549b2020-08-07 11:54:28 +010045from .tensor import create_const_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 Gustavsson3a269202021-01-21 08:28:55 +010062def rewrite_concat_ops(op, arch, nng):
63 if not op.run_on_npu or not op.type.is_concat_op():
64 return op
Tim Hall79d07d22020-04-27 18:20:16 +010065
Patrik Gustavsson3a269202021-01-21 08:28:55 +010066 axis_4D = 0
67 ofm = op.ofm
68 ofm.ops = []
69 offset = 0
Tim Hall79d07d22020-04-27 18:20:16 +010070
Patrik Gustavsson7bada402021-01-28 15:46:21 +010071 unfuse_activation_function(op)
72
Patrik Gustavsson3a269202021-01-21 08:28:55 +010073 if op.type == Op.Pack:
74 # Pack is also referred to as Stack
75 axis = int(op.attrs["axis"])
76 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +010077
Patrik Gustavsson3a269202021-01-21 08:28:55 +010078 if axis >= 0:
79 axis_4D = axis + (4 - len(desired_shape))
80 else:
81 axis_4D = axis
82
83 for idx, inp in enumerate(op.inputs):
84 op.ifm_shapes[idx] = Shape4D(desired_shape)
85 if Shape4D(inp.shape) != op.ifm_shapes[idx]:
86 inp.avoid_NHCWB16 = True
87 op.type = Op.PackReshaped
88
89 inputs, axis = op.get_concat_inputs_axis()
90
91 for idx, inp in enumerate(inputs):
92 if op.type != Op.PackReshaped:
93 op.ifm_shapes[idx] = Shape4D(inp.shape)
Patrik Gustavsson3d737172020-12-22 10:40:51 +010094 if axis >= 0:
95 axis_4D = axis + (4 - len(inp.shape))
96 else:
97 axis_4D = axis
Patrik Gustavsson3a269202021-01-21 08:28:55 +010098 new_op = Operation(Op.ConcatSliceWrite, op.name + str(idx))
99 new_op.inputs = [inp]
100 new_op.outputs = [ofm]
101 new_op.attrs["concat_axis"] = axis_4D
102 new_op.attrs["concat_start"] = offset
103 offset += op.ifm_shapes[idx].get_dim(axis_4D)
Tim Hall79d07d22020-04-27 18:20:16 +0100104
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100105 new_op.attrs["concat_end"] = offset
106 new_op.run_on_npu = True
107 ofm.ops.append(new_op)
108 DebugDatabase.add_optimised(op, new_op)
109 new_op.ifm_shapes.append(op.ifm_shapes[idx].clone())
110 new_op.ofm_shapes.append(op.ofm_shapes[0].clone())
111 assert ofm.shape[axis] == offset
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200112
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100113 # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a
114 # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte
115 # aligned. For other values of axis the address offsets will be 16 byte aligned, as they are all based on c = 0
116 # and those addresses are always 16 byte aligned due to the NHCWB16 format.
117 if axis == -1 or axis == (len(ofm.shape) - 1):
118 for op in ofm.ops:
119 if op.attrs["concat_start"] % 16 != 0:
120 ofm.avoid_NHCWB16 = True
121 break
122 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100123
124
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100125def rewrite_split_ops(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100126
Patrik Gustavsson224e99b2021-01-14 10:55:43 +0100127 if len(tens.ops) == 1 and tens.ops[0].type.is_split_op() and tens.ops[0].type != Op.Unpack:
Tim Hall79d07d22020-04-27 18:20:16 +0100128 split_op = tens.ops[0]
129
130 # Not supported so leave it and run on CPU
131 if not split_op.run_on_npu:
132 return tens
133
134 inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis()
135
136 tens.ops = []
Louis Verhaardaee5d752020-09-30 09:01:52 +0200137 new_op = Operation(Op.SplitSliceRead, split_op.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100138 new_op.inputs = [inp]
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100139 ofm_shape_idx = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100140
141 # For Split the offset cannot be extracted from the tensor so it has to
142 # be calculated from the index of the output tensor
Diego Russoea6111a2020-04-14 18:41:58 +0100143 if axis is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100144 # Get the start and end of the split
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100145 offset_start = [0] * 4
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100146 axis_4D_list = split_op.attrs.get("split_axis_4D", None) # Present for UnpackReshaped and some StridedSlice
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100147 for idx, out in enumerate(outputs):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100148 if axis_4D_list is not None:
149 axis_4D = axis_4D_list[idx]
Patrik Gustavsson3d737172020-12-22 10:40:51 +0100150 else:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100151 split_op.ofm_shapes[idx] = Shape4D(out.shape)
152 if axis >= 0:
153 axis_4D = axis + (4 - len(out.shape))
154 else:
155 axis_4D = axis
156
157 if out == tens:
158 ofm_shape_idx = idx
159 break
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000160
161 offset_start[axis_4D] += split_op.ofm_shapes[idx].get_dim(axis_4D)
Tim Hall79d07d22020-04-27 18:20:16 +0100162
Patrik Gustavssoneebb1c22020-08-18 15:03:04 +0200163 # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input
164 if (offset_start[-1] % 16) != 0:
165 inp.avoid_NHCWB16 = True
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100166 else:
167 offset_start = full_shape(4, offset_start, 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100168
169 new_op.attrs["split_start"] = offset_start
Tim Hall79d07d22020-04-27 18:20:16 +0100170 new_op.run_on_npu = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100171 new_op.set_output_tensor(tens)
Patrik Gustavsson224e99b2021-01-14 10:55:43 +0100172 new_op.ifm_shapes.append(Shape4D(inp.shape))
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100173 new_op.ofm_shapes.append(split_op.ofm_shapes[ofm_shape_idx].clone())
Tim Halle6ccd872020-11-09 16:46:37 +0000174 DebugDatabase.add_optimised(split_op, new_op)
Tim Hall79d07d22020-04-27 18:20:16 +0100175
176 return tens
177
178
179def needed_total_padding(input_size, stride, filter_size):
180 out_size = (input_size + stride - 1) // stride
181 needed_input = (out_size - 1) * stride + filter_size
182 total_padding = max(0, needed_input - input_size)
183 return total_padding
184
185
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100186def calc_padding_and_skirt(padding_type, kernel_size, stride, input_shape, explicit_padding):
187 ypad = needed_total_padding(int(input_shape.height), int(stride[1]), int(kernel_size[0]))
188 xpad = needed_total_padding(int(input_shape.width), int(stride[2]), int(kernel_size[1]))
Michael McGeagh16895482020-12-14 15:51:20 +0000189 if padding_type == Padding.SAME:
Tim Hall79d07d22020-04-27 18:20:16 +0100190 left_pad = (xpad + 0) // 2
191 right_pad = (xpad + 1) // 2
192 top_pad = (ypad + 0) // 2
193 bottom_pad = (ypad + 1) // 2
Michael McGeagh16895482020-12-14 15:51:20 +0000194 elif padding_type == Padding.VALID:
Tim Hall79d07d22020-04-27 18:20:16 +0100195 left_pad = 0
196 right_pad = 0
197 top_pad = 0
198 bottom_pad = 0
Louis Verhaardae2d5532020-12-11 17:19:54 +0100199 elif padding_type == Padding.EXPLICIT:
200 # Padding is specified in a PAD operator which has been bypassed.
201 # The top and left padding are taken from the PAD; bottom and right are calculated.
202 top_pad, left_pad, _, _ = explicit_padding
203 bottom_pad = ypad - top_pad
204 right_pad = xpad - left_pad
Tim Hall79d07d22020-04-27 18:20:16 +0100205 else:
Michael McGeagh16895482020-12-14 15:51:20 +0000206 raise UnsupportedFeatureError(f"Unknown padding")
Tim Hall79d07d22020-04-27 18:20:16 +0100207 padding = (top_pad, left_pad, bottom_pad, right_pad)
208 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
209 return padding, skirt
210
Tim Hallc30f4952020-06-15 20:47:35 +0100211
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100212def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_shape, upscaling_factor):
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200213 kernel_height, kernel_width = kernel_size[0], kernel_size[1]
Michael McGeagh16895482020-12-14 15:51:20 +0000214 if padding_type == Padding.SAME:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100215 ypad = needed_total_padding(int(input_shape.height) * upscaling_factor, int(stride[1]), int(kernel_height))
216 xpad = needed_total_padding(int(input_shape.width) * upscaling_factor, int(stride[2]), int(kernel_width))
Jacob Bohlind47cc272020-08-24 11:42:14 +0200217 right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0)
218 bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200219 left_pad = max(kernel_width - 1 - right_pad, 0)
220 top_pad = max(kernel_height - 1 - bottom_pad, 0)
Michael McGeagh16895482020-12-14 15:51:20 +0000221 elif padding_type == Padding.VALID:
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200222 right_pad = max(kernel_width - 2, 0)
223 bottom_pad = max(kernel_height - 2, 0)
224 left_pad = kernel_width - 1
225 top_pad = kernel_height - 1
Jacob Bohlincf7da102020-05-20 09:03:40 +0200226 else:
Michael McGeagh16895482020-12-14 15:51:20 +0000227 raise UnsupportedFeatureError(f"Unknown padding")
Jacob Bohlincf7da102020-05-20 09:03:40 +0200228 padding = (top_pad, left_pad, bottom_pad, right_pad)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200229 skirt = padding
Jacob Bohlincf7da102020-05-20 09:03:40 +0200230 return padding, skirt
231
Tim Hall79d07d22020-04-27 18:20:16 +0100232
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200233def fixup_conv2d_backprop(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200234 if op.type == Op.Conv2DBackpropInput:
Tim Hall79d07d22020-04-27 18:20:16 +0100235 # flip the inputs
236 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000237 op.set_ifm_ofm_shapes()
Louis Verhaardaee5d752020-09-30 09:01:52 +0200238 op.type = Op.Conv2DBackpropInputSwitchedBias
Louis Verhaard69b84802020-12-16 12:02:28 +0100239 op.ifm.resampling_mode = resampling_mode.TRANSPOSE
Jacob Bohlincf7da102020-05-20 09:03:40 +0200240
241 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100242 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100243
244 return op
245
246
Charles Xu9a03fdf2020-07-02 15:12:40 +0200247# Convert the op to an elementwise add
248def convert_resizebilinear_1x1_to_add(op):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200249 op.type = Op.Add
Charles Xu9a03fdf2020-07-02 15:12:40 +0200250 op.name = op.name + "_add"
Charles Xu9a03fdf2020-07-02 15:12:40 +0200251 op.attrs["resizebilinear"] = True
252 # Create an input tensor filled with zeros
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100253 shape = op.ofm_shapes[0].as_list()
Charles Xu9a03fdf2020-07-02 15:12:40 +0200254 tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add")
255 tens.values = np.zeros(shape)
256 tens.quant_values = np.zeros(shape, np.uint8)
257 tens.quantization = QuantizationParameters(0.0, 255.0)
258 tens.quantization.scale_f32 = 1.0
259 tens.quantization.zero_point = 0
260 tens.consumer_list = [op]
261 tens_op = op.inputs[1].ops[0]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100262 tens_op.set_output_tensor(tens)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200263 # Set the add inputs
264 op.inputs[1] = op.inputs[0]
265 op.inputs[0] = tens
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000266 op.set_ifm_ofm_shapes()
Charles Xu9a03fdf2020-07-02 15:12:40 +0200267
268 return op
269
270
Charles Xu87c13502020-08-06 12:17:26 +0200271# Convert ResizeBilinear to a number of 2x2 pool ops
272def convert_resizebilinear_to_2x2_pool(op):
273 count = 0
274 pre_op = op
275 outputs = op.outputs
276
277 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
278 if op.attrs["align_corners"]:
279 shape_modifier = 1
Michael McGeagh16895482020-12-14 15:51:20 +0000280 op.attrs["padding"] = Padding.VALID
Charles Xu87c13502020-08-06 12:17:26 +0200281 else:
282 shape_modifier = 0
Michael McGeagh16895482020-12-14 15:51:20 +0000283 op.attrs["padding"] = Padding.SAME
Charles Xu87c13502020-08-06 12:17:26 +0200284 op.inputs[0].resampling_mode = resampling_mode.NEAREST
285
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100286 upscaled_shape = op.ifm_shape[0].get_hw_as_list()
287 out_shape = op.ofm_shape[0].get_hw_as_list()
Charles Xu87c13502020-08-06 12:17:26 +0200288 if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all():
289 return op
290
291 while (upscaled_shape < out_shape).all():
292 if count == 0:
293 scaled_op = pre_op
294 else:
295 scaled_op = op.clone("_{}".format(count))
296 scaled_op.inputs[0] = pre_op.outputs[0]
297
298 upscaled_shape = upscaled_shape * 2 - shape_modifier
299
300 if (upscaled_shape == out_shape).all():
301 scaled_op.outputs = outputs
302 scaled_op.outputs[0].ops = [scaled_op]
303 else:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100304 shape = op.ofm_shapes[0].as_list()
305 shape[1:3] = upscaled_shape
Charles Xu87c13502020-08-06 12:17:26 +0200306 out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count))
307 out_tens.quantization = op.outputs[0].quantization.clone()
308 out_tens.quantization.quant_min = np.iinfo(np.int16).min
309 out_tens.quantization.quant_max = np.iinfo(np.int16).max
310 scaled_op.set_output_tensor(out_tens)
311 pre_op = scaled_op
312 count += 1
313
314 # Setup the scale value
315 if scaled_op.inputs[0].dtype.bits == 8 and scaled_op.outputs[0].dtype.bits == 16:
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100316 scaled_op.rescale = 128
Charles Xu87c13502020-08-06 12:17:26 +0200317 elif scaled_op.inputs[0].dtype.bits == 16 and scaled_op.outputs[0].dtype.bits == 8:
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100318 scaled_op.rescale = 1 / 128
319 else:
320 scaled_op.rescale = None
Patrik Gustavssoncc6915c2020-12-22 09:16:50 +0100321 scaled_op.set_ifm_ofm_shapes()
Charles Xu87c13502020-08-06 12:17:26 +0200322
323 return op
324
325
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200326def fixup_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200327 if op.type == Op.ResizeBilinear and op.run_on_npu:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100328 if op.ifm_shapes[0] == op.ofm_shapes[0]:
Charles Xu36ffaf32020-08-05 15:40:44 +0200329 # Bypass nop resizebilinear
330 op.inputs = op.inputs[:1]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200331 op.type = Op.Identity
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100332 elif op.ifm_shapes[0].height == 1 and op.ifm_shapes[0].width == 1:
Charles Xu87c13502020-08-06 12:17:26 +0200333 convert_resizebilinear_1x1_to_add(op)
334 else:
335 convert_resizebilinear_to_2x2_pool(op)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200336
337 return op
338
339
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200340def convert_nop_split_to_identity(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200341 if op.type == Op.Split and op.attrs.get("num_splits") == 1:
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200342 # the list comprehension should return a list with a single tensor
343 # if it shouldn't, remove_passthrough_tensor will fail appropriately
344 op.inputs = [i for i in op.inputs if i.shape == op.outputs[0].shape]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200345 op.type = Op.Identity
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200346 return op
347
348
Diqing Zhong94457b12020-12-09 15:22:40 +0100349def convert_batched_fc_shape(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200350 if op.type == Op.FullyConnected:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100351 # Check if the first dimension indicates batching
352 if op.ifm_shapes[0].batch > 1:
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200353 batching_split = {4: (2, 2), 8: (2, 4), 16: (4, 4)}
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100354 n = op.ifm_shapes[0].batch
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200355 h, w = batching_split.get(n, (1, n))
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100356 op.ifm_shapes[0] = Shape4D([1, h, w, op.ifm_shapes[0].depth])
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200357
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100358 op.ifm.avoid_NHCWB16 = True
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200359
360 # Reshape Weights to be 4D. IO becomes HWIO
361 weight_tensor = op.inputs[1]
362 weight_tensor.quant_values = np.expand_dims(np.expand_dims(weight_tensor.quant_values, axis=0), axis=0)
363 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
364
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100365 n = op.ofm_shapes[0].batch
366 h, w = batching_split.get(n, (1, n))
367 op.ofm_shapes[0] = Shape4D([1, h, w, op.ofm_shapes[0].depth])
368 op.ofm.avoid_NHCWB16 = True
Tim Hall79d07d22020-04-27 18:20:16 +0100369 return op
370
371
Patrik Gustavsson7bada402021-01-28 15:46:21 +0100372def unfuse_activation_function(op):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200373 if op.type == Op.ConcatTFLite and op.run_on_npu and op.activation is not None:
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100374 act_op = Operation(op.activation.op_type, op.name + op.activation.op_type.name)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200375 op.activation = None
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200376 out_tens = op.outputs[0]
377 intermediate_tens = out_tens.clone("_act_intermediate")
378 act_op.set_output_tensor(out_tens)
379 act_op.add_input_tensor(intermediate_tens)
380 op.set_output_tensor(intermediate_tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000381 act_op.set_ifm_ofm_shapes()
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200382
Louis Verhaard8912c532020-09-30 12:11:49 +0200383
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100384def rewrite_stridedslice_output(op, arch, nng):
385 if not op.run_on_npu or op.type != Op.StridedSlice:
386 return op
387
388 new_axis_mask = op.attrs["new_axis_mask"]
389 shrink_axis_mask = op.attrs["shrink_axis_mask"]
390
391 if shrink_axis_mask == 0 and new_axis_mask == 0:
392 return op
393
394 axis_4D = [0] * len(op.outputs)
395 for idx, out_tens in enumerate(op.outputs):
396 output_shape = list(out_tens.shape)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100397
Dwight Lidman73320a42020-11-05 10:34:41 +0100398 if shrink_axis_mask != 0:
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100399 n = 0
400 axis = 0
401 while shrink_axis_mask:
402 prev_mask = shrink_axis_mask
403 n += 1
404 shrink_axis_mask &= shrink_axis_mask - 1
405 axis = int(math.log2(prev_mask - shrink_axis_mask))
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100406 output_shape = output_shape[:axis] + [1] + output_shape[axis:]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100407
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100408 assert len(out_tens.shape) == (len(op.inputs[0].shape) - n)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100409 op.attrs["shrink_axis_mask"] = 0
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100410 if axis >= 0:
411 axis_4D[idx] = axis + (4 - len(output_shape))
412 else:
413 axis_4D[idx] = axis
414 op.ofm_shapes[idx] = Shape4D(output_shape)
415
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100416 elif new_axis_mask != 0:
417 n = 0
418 axis = 0
419 while new_axis_mask:
420 prev_mask = new_axis_mask
421 n += 1
422 new_axis_mask &= new_axis_mask - 1
423 axis = int(math.log2(prev_mask - new_axis_mask))
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100424 output_shape = output_shape[:axis] + output_shape[(axis + 1) :]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100425 new_axis_mask >>= 1
426
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100427 assert len(out_tens.shape) == (len(op.inputs[0].shape) + n)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100428 op.attrs["new_axis_mask"] = 0
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100429 if axis >= 0:
430 axis_4D[idx] = axis + (4 - len(output_shape))
431 else:
432 axis_4D[idx] = axis
433 op.ofm_shapes[idx] = Shape4D(output_shape)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100434
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100435 if op.ofm_shapes[idx] != Shape4D(out_tens.shape):
436 out_tens.avoid_NHCWB16 = True
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100437
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100438 op.attrs["split_axis_4D"] = axis_4D
439 return op
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100440
441
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100442def rewrite_unpack_output(op, arch, nng):
443 tens = op.outputs[0]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100444 if op.run_on_npu and op.type == Op.Unpack:
Tim Hall79d07d22020-04-27 18:20:16 +0100445 # Unpack is also referred to as Unstack
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100446 axis = int(op.attrs["axis"])
447 op.type = Op.UnpackReshaped
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100448 desired_output_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100449
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100450 if axis >= 0:
451 axis_4D = axis + (4 - len(desired_output_shape))
452 else:
453 axis_4D = axis
Tim Hall79d07d22020-04-27 18:20:16 +0100454
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100455 axis_4D_list = [0] * len(op.outputs)
Tim Hall79d07d22020-04-27 18:20:16 +0100456 for idx, out_tens in enumerate(op.outputs):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100457 op.ofm_shapes[idx] = Shape4D(desired_output_shape)
458 axis_4D_list[idx] = axis_4D
459 if op.ofm_shapes[idx] != Shape4D(out_tens.shape):
460 out_tens.avoid_NHCWB16 = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100461
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100462 op.attrs["split_axis_4D"] = axis_4D_list
463 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100464
465
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200466def add_padding_fields(op, arch, nng):
Jacob Bohlin90033f32020-08-28 15:45:44 +0200467 if op.run_on_npu:
468 if "padding" in op.attrs:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100469 input_shape = op.ifm_shapes[0]
470 output_shape = op.ofm_shapes[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200471 if op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op():
Jacob Bohlin90033f32020-08-28 15:45:44 +0200472 kernel_size = op.inputs[1].shape[:2]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200473 elif op.type.is_pool_op() or op.type.npu_block_type == NpuBlockType.ReduceSum:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200474 kernel_size = op.attrs["ksize"][1:3]
Jacob Bohlin90033f32020-08-28 15:45:44 +0200475 else:
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000476 raise UnsupportedFeatureError(f"Unknown operation that uses padding: {optype_to_builtintype(op.type)}")
Tim Hall79d07d22020-04-27 18:20:16 +0100477
Louis Verhaardaee5d752020-09-30 09:01:52 +0200478 if op.type == Op.Conv2DBackpropInputSwitchedBias:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100479 upscaling_factor = output_shape.height // input_shape.height
Jacob Bohlin90033f32020-08-28 15:45:44 +0200480 padding, skirt = calc_upscaled_padding_and_skirt(
481 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
482 )
483 else:
484 dilation_h, dilation_w = op.get_dilation_h_w()
485 dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1]
486 padding, skirt = calc_padding_and_skirt(
Louis Verhaardae2d5532020-12-11 17:19:54 +0100487 op.attrs["padding"],
488 dilated_kernel_size,
489 op.attrs["strides"],
490 input_shape,
491 op.attrs.get("explicit_padding"),
Jacob Bohlin90033f32020-08-28 15:45:44 +0200492 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200493
Jacob Bohlin90033f32020-08-28 15:45:44 +0200494 op.attrs["explicit_padding"] = padding
495 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200496
Tim Hall79d07d22020-04-27 18:20:16 +0100497 return op
498
499
Tim Hall79d07d22020-04-27 18:20:16 +0100500# Check if the op can be reordered
501def get_prepend_op(op):
502 inp = op.inputs[0]
503 # The op should be reordered between prev_op and prep_op
504 prev_op = inp.ops[-1]
505 prep_op = None
506 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
507 prep_op = prev_op
508 inp = prev_op.inputs[0]
509 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100510 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 +0100511 return prep_op
512
513 return None
514
515
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200516def convert_depthwise_to_conv(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100517 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
518 # the ofm depth equals the depth multipler.
519 # If those conditions are true, then we can perform a simple
520 # switch of the operator type (and weight order)
521
Louis Verhaardaee5d752020-09-30 09:01:52 +0200522 if op.type == Op.DepthwiseConv2DBias and (op.attrs["depth_multiplier"] != 1):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100523 ifm_shape = op.ifm_shapes[0]
Tim Hall79d07d22020-04-27 18:20:16 +0100524 weight_tensor = op.inputs[1]
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100525 ofm_shape = op.ofm_shapes[0]
526 if (ifm_shape.depth == 1) and (ofm_shape.depth == op.attrs["depth_multiplier"]):
Tim Hall79d07d22020-04-27 18:20:16 +0100527 # Change op type to Conv2d
Louis Verhaardaee5d752020-09-30 09:01:52 +0200528 op.type = Op.Conv2DBias
Tim Hall79d07d22020-04-27 18:20:16 +0100529 del op.attrs["channel_multiplier"]
530 del op.attrs["depth_multiplier"]
531
532 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100533 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100534 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200535 raise UnsupportedFeatureError(
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000536 f"Unsupported 'DEPTHWISE_CONV_2D' with depth_multiplier = {op.attrs['depth_multiplier']},",
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100537 f" ifm channels = {ifm_shape.depth}, ofm channels = {ofm_shape.depth}",
Tim Hall79d07d22020-04-27 18:20:16 +0100538 )
Tim Halle6ccd872020-11-09 16:46:37 +0000539 DebugDatabase.add_optimised(op, op)
Tim Hall79d07d22020-04-27 18:20:16 +0100540 return op
541
542
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200543def reorder_depthwise_weights(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200544 if op.type.is_depthwise_conv2d_op():
Jacob Bohline843d332020-06-23 12:12:56 +0200545 weight_tensor = op.inputs[1]
546 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100547 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200548 weight_tensor.weight_transpose_depthwise = True
549
550 return op
551
552
Diqing Zhong016b8272020-12-16 16:46:06 +0100553def optimise_strided_conv(op, arch, nng):
554 stride_x, stride_y = op.get_kernel_stride()
555 ifm_tensor, _, weight_tensor, _ = op.get_ifm_ifm2_weights_ofm()
556
557 if (
558 op.type == Op.Conv2DBias
559 and op.op_index == 0
560 and stride_x == 2
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100561 and op.ifm_shapes[0].depth <= 4
562 and op.ifm_shapes[0].width % 2 == 0
Diqing Zhong016b8272020-12-16 16:46:06 +0100563 and weight_tensor is not None
564 and weight_tensor.shape[1] >= 2
565 ):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100566 ifm_shape = op.ifm_shapes[0]
Diqing Zhong016b8272020-12-16 16:46:06 +0100567 # IFM
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100568 op.ifm_shapes[0] = Shape4D([ifm_shape.batch, ifm_shape.height, ifm_shape.width // 2, ifm_shape.depth * 2])
569 op.ifm.avoid_NHCWB16 = True
Diqing Zhong016b8272020-12-16 16:46:06 +0100570
571 # Weights
572 weight_shape = weight_tensor.shape
573 if weight_shape[1] % 2 != 0:
574 weight_shape[1] = weight_shape[1] + 1
575 padded_array = np.zeros(weight_shape)
576 for i in range(weight_shape[0]):
577 padded_array[i] = np.vstack(
578 [
579 weight_tensor.quant_values[i],
580 np.full((1, weight_shape[2], weight_shape[3]), weight_tensor.quantization.zero_point),
581 ]
582 )
583 weight_tensor.quant_values = padded_array
584 weight_shape[1] //= 2
585 weight_shape[2] *= 2
586 weight_tensor.quant_values = np.reshape(weight_tensor.quant_values, weight_shape)
587 weight_tensor.set_all_shapes(weight_shape)
588 # If multiple copies of the weights are used, we could avoid
589 # them having the same address by changing the value_id
590 weight_tensor.value_id = uuid.uuid4()
591
592 # Strides
593 stride_x = 1
594 op.attrs.update({"stride_w": stride_x, "stride_h": stride_y, "strides": (1, stride_y, stride_x, 1)})
595
Diqing Zhong016b8272020-12-16 16:46:06 +0100596 return op
597
598
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200599def convert_conv_to_fc(op, arch, nng):
Michael McGeagh8d939c02020-07-29 13:11:43 +0100600 # Conv 1x1 can be equivalent to Fully Connected.
601 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
602 # caching/double buffering for the weights.
603 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200604 if op.type == Op.Conv2DBias:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000605 h = op.ifm_shapes[0].height
606 w = op.ifm_shapes[0].width
Michael McGeagh8d939c02020-07-29 13:11:43 +0100607 kh, kw, _, _ = op.inputs[1].shape
608 if h == 1 and w == 1 and kh == 1 and kw == 1:
609 # Overwrite this op as a Fully Connected Op
610 op.name += "_fc"
Louis Verhaardaee5d752020-09-30 09:01:52 +0200611 op.type = Op.FullyConnected
Michael McGeagh8d939c02020-07-29 13:11:43 +0100612 op.attrs = {
Michael McGeagh8d939c02020-07-29 13:11:43 +0100613 "weights_format": 0,
Michael McGeagh8d939c02020-07-29 13:11:43 +0100614 }
615 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
616 weight_tensor = op.inputs[1]
617 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
618 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100619
Tim Halle6ccd872020-11-09 16:46:37 +0000620 DebugDatabase.add_optimised(op, op)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100621 return op
622
623
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200624def fixup_relus_with_differing_ifm_ofm_scaling(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200625 if op.run_on_npu and op.type.is_relu_op():
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100626 ifm = op.inputs[0]
627 ofm = op.outputs[0]
628 # Relu with differing IFM and OFM scaling cannot be fused with another primary op
629 # and requires its own to be inserted
Tim Hall93582962020-09-09 21:58:15 +0100630 if not check_quantized_tens_scaling_equal(ifm, ofm):
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100631 # Override this op with its own primary op (avgpool)
632 relu_fused_op = create_avgpool_nop(op.name + "_avgpool")
633 # And fuse the original activation function to it
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100634 relu_fused_op.activation = create_activation_function(op.type)
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100635 # Tidy up and assign the ifm and ofm to the new op
636 ifm.consumer_list.remove(op)
Andreas Nevalainenf3d737e2020-09-25 14:12:43 +0200637
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100638 relu_fused_op.add_input_tensor(ifm)
639 relu_fused_op.set_output_tensor(ofm)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000640 relu_fused_op.set_ifm_ofm_shapes()
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100641 op = relu_fused_op
642 return op
643
644
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100645# TODO remove if mem only ops can all be removed
Tim Hall79d07d22020-04-27 18:20:16 +0100646# Reorder activation op if it's after the memory only operations
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200647def fixup_act_reorder(op, arch, nng):
Michael McGeaghf3e3ad72020-12-02 12:39:03 +0000648 if op.type.is_relu_op() or op.type in (Op.Sigmoid, Op.Tanh):
Tim Hall79d07d22020-04-27 18:20:16 +0100649 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100650 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100651 act_op = op.clone("_reordered")
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100652 act_op.ifm_shapes = list(op.ifm_shapes)
653 act_op.ofm_shapes = list(op.ofm_shapes)
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200654
655 # There is only one input tensor, overwrite it
656 act_op.set_input_tensor(prep_op.inputs[0], 0)
657
Tim Hall79d07d22020-04-27 18:20:16 +0100658 act_op_out = act_op.inputs[0].clone("_acted")
659 act_op_out.quantization = op.outputs[0].quantization.clone()
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100660 act_op.set_output_tensor(act_op_out)
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100661 act_op.ofm_shapes[0] = act_op.ifm_shapes[0].clone()
662 act_op.ifm_shapes[0] = prep_op.ifm_shapes[0].clone()
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200663
664 # Update the consumer list
665 act_op_out.consumer_list = op.outputs[0].consumer_list.copy()
666 act_op_out.consumer_list.append(prep_op)
667
Tim Hall79d07d22020-04-27 18:20:16 +0100668 prep_op.inputs[0] = act_op_out
669 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
670
671 # Mark the op so that it will be removed as passthrough later on
Louis Verhaardaee5d752020-09-30 09:01:52 +0200672 op.type = Op.Identity
Tim Halle6ccd872020-11-09 16:46:37 +0000673
674 # Record optimisation in debug database
675 DebugDatabase.add_optimised(op, act_op)
676 DebugDatabase.add_optimised(op, op)
Tim Hall79d07d22020-04-27 18:20:16 +0100677 return op
678
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200679
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200680def fixup_elementwise_with_scalars(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200681 if op.type.is_binary_elementwise_op():
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200682 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200683 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
684 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
685 if diff > 0:
686 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
687 elif diff < 0:
688 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200689 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
690 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
691 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
692 ifm_tensor.storage_shape = ifm_tensor.shape
693 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
694 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
695 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
696 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200697 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100698
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200699
Tim Hall4e127762020-05-15 16:05:49 +0100700# Set input/output tensor equivalence to the same id for memory operations
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200701def set_tensor_equivalence(op, arch, nng):
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100702 if op.type in memory_only_ops:
Tim Hall4e127762020-05-15 16:05:49 +0100703 eid = op.outputs[0].equivalence_id
704 for inp in op.inputs:
705 inp.equivalence_id = eid
706 return op
707
708
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100709def set_ifm_ofm_op_shapes(op, arch, nng):
710 if op.run_on_npu and op.type.needs_shapes():
711 if op.ifm_shapes or op.ofm_shapes:
712 # Shapes already set
713 return op
714 op.set_ifm_ofm_shapes()
715 return op
716
717
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200718def convert_softmax(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200719 if op.type == Op.Softmax and op.run_on_npu:
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200720 softmax = SoftMax(op)
721 op = softmax.get_graph()
722 return op
723
724
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200725def convert_mul_max_to_abs_or_lrelu(op, arch, nng):
Diego Russoea6111a2020-04-14 18:41:58 +0100726 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100727
728 Input X For X = -1 or X > 0
729 | \ / This subgraph can be replaced with either
730 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
731 | /
732 Max
733 """
734
Louis Verhaardaee5d752020-09-30 09:01:52 +0200735 if op.type == Op.Maximum:
Tim Hall79d07d22020-04-27 18:20:16 +0100736 # finds the Mul input(s) to the Max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200737 muls = [i for i in op.inputs if i.ops[0].type == Op.Mul]
Tim Hall79d07d22020-04-27 18:20:16 +0100738 if len(muls) == 1:
739 mul = muls[0].ops[0]
740 elif len(muls) == 2:
741 # In the case both inputs are Muls, find the one with the same input as the Max
742 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
743 else:
744 # No Mul inputs
745 return op
746
747 # make sure the Mul doesn't have any other consumers
Louis Verhaardd7911c42020-08-25 13:36:41 +0200748 mul_ofm = mul.outputs[0]
749 if len(mul_ofm.consumers()) != 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100750 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200751 # make sure the Mul doesn't have a fused activation function
752 if mul.activation:
Tim Hall79d07d22020-04-27 18:20:16 +0100753 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200754 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100755 if ifm is None or ofm is None:
756 return op
757
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200758 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
759 return op
Tim Hall93582962020-09-09 21:58:15 +0100760 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 +0200761 # rewrite to LeakyRelu currently only makes sense if the quantization is identical
762 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100763
764 # finds the branched input that goes to both the Max and the Mul
765 shared = set(op.inputs) & set(mul.inputs)
766 if len(shared) == 1:
767 shared_in = shared.pop()
768 # find the constant scalar input to the Mul
769 const_tens = (set(mul.inputs) - {shared_in}).pop()
770 # check that it is a scalar
771 if const_tens.shape != []:
772 return op
773 const = const_tens.ops[0]
774 # check that it is a constant
Louis Verhaardaee5d752020-09-30 09:01:52 +0200775 if const.type != Op.Const:
Tim Hall79d07d22020-04-27 18:20:16 +0100776 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200777 # Remove the Mul from the shared input's consumers
778 shared_in.consumer_list.remove(mul)
Tim Hall79d07d22020-04-27 18:20:16 +0100779 else:
780 return op
781
782 val = const.outputs[0].values
783 if val >= 0:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200784 new_op = Op.LeakyRelu
Tim Hall79d07d22020-04-27 18:20:16 +0100785 op.attrs["alpha"] = val
Louis Verhaardd7911c42020-08-25 13:36:41 +0200786 # to produce bit exact results, the alpha is not enough;
787 # save additional scaling info in attr "alpha_scale", to be used as input
788 # to the LUT construction
789 alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point
790 mul_ifm_scale = np.double(ifm.quantization.scale_f32)
791 mul_ifm2_scale = np.double(const_tens.quantization.scale_f32)
792 mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32)
793 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale)
794 op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift)
Tim Hall79d07d22020-04-27 18:20:16 +0100795 elif val == -1:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200796 new_op = Op.Abs
Tim Hall79d07d22020-04-27 18:20:16 +0100797 else:
798 return op
799
Louis Verhaardaee5d752020-09-30 09:01:52 +0200800 op.type = new_op
801 op.name = op.name.replace("Maximum", new_op.name)
802 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100803 op.inputs = [shared_in]
Patrik Gustavssonc509d332020-12-22 13:53:52 +0100804 op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000805
806 # Record optimisation in debug database
807 DebugDatabase.add_optimised(op, op)
808
Tim Hall79d07d22020-04-27 18:20:16 +0100809 return op
810
811
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200812def convert_lrelu_to_mul_max(op, arch):
813 # Converts LeakyRelu to Max(alpha * IFM, identity * IFM)
814 # (the opposite of convert_mul_max_to_abs_or_lrelu)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200815 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100816 if ifm is None or ofm is None:
817 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200818
819 # Add multiplication with alpha
Louis Verhaardaee5d752020-09-30 09:01:52 +0200820 mul_alpha = Operation(Op.Mul, op.name + "_mul_alpha")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200821 mul_alpha.add_input_tensor(ifm)
822 # Create const tensor containing alpha as scalar
823 alpha = op.attrs["alpha"]
824 quantization = ifm.quantization.clone()
825 quantization.min = 0
826 quantization.max = alpha * (quantization.quant_max - quantization.quant_min)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200827 quantization.zero_point = 0
Louis Verhaardece4e652021-01-07 13:35:47 +0100828 if np.isinf(1 / np.float32(alpha)):
829 # Handling of alpha near zero
830 quantization.scale_f32 = 1
831 scalar = 0
832 else:
833 quantization.scale_f32 = alpha
834 scalar = 1
835 alpha_tens = create_const_tensor(
836 op.name + "_alpha_scalar", [], ifm.dtype, [scalar], np.int8, quantization=quantization
837 )
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200838 mul_alpha.add_input_tensor(alpha_tens)
839 fm_alpha = ofm.clone(op.name + "_alpha")
840 mul_alpha.set_output_tensor(fm_alpha)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000841 mul_alpha.set_ifm_ofm_shapes()
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)
Louis Verhaardece4e652021-01-07 13:35:47 +0100861 # Make sure that fm_id is allocated to a different address than fm_alpha
862 fm_id = ofm.clone(op.name + "_id", set_unique=True)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200863 mul_identity.set_output_tensor(fm_id)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000864 mul_identity.set_ifm_ofm_shapes()
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100865 DebugDatabase.add_optimised(op, mul_identity)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200866
867 # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs
Louis Verhaardaee5d752020-09-30 09:01:52 +0200868 op.type = Op.Maximum
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200869 op.name = op.name.replace("LeakyRelu", "Maximum")
870 op.inputs = []
871 ifm.consumer_list.remove(op)
872 op.add_input_tensor(fm_alpha)
873 op.add_input_tensor(fm_id)
Patrik Gustavssonc509d332020-12-22 13:53:52 +0100874 op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000875
876 DebugDatabase.add_optimised(op, op)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200877 return op
878
879
Louis Verhaard2e186c72020-10-09 10:47:04 +0200880def convert_to_lut(op, lut_values, lut_name):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200881 # Rewrite the operation by Add with scalar 0 + LUT activation
882 ifm = op.inputs[0]
Tim Hall93582962020-09-09 21:58:15 +0100883 if ifm is None:
884 return op
Louis Verhaard58520b92020-08-24 16:45:38 +0200885 assert ifm.dtype.size_in_bytes() == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +0200886 op.type = Op.Add
Louis Verhaard2e186c72020-10-09 10:47:04 +0200887 op.name = op.name + "_lut_" + lut_name
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200888 # Mark as no-op to enable potential fusing optimizations
889 op.attrs["is_nop"] = True
890 # Create an input tensor containing scalar zero
891 quantization = QuantizationParameters(0.0, 255.0)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200892 quantization.scale_f32 = ifm.quantization.scale_f32
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200893 quantization.zero_point = 0
Louis Verhaard2e186c72020-10-09 10:47:04 +0200894 tens = create_const_tensor(op.inputs[0].name + "_scalar0", [], ifm.dtype, [0], np.uint8, quantization=quantization)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200895 op.add_input_tensor(tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000896 op.ifm_shapes.append(Shape4D(tens.shape))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100897
Louis Verhaardf03bad32020-09-25 08:30:44 +0200898 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
899 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
900 # should be the same as the IFM
Louis Verhaardaee5d752020-09-30 09:01:52 +0200901 op.forced_output_quantization = ifm.quantization
Louis Verhaard2e186c72020-10-09 10:47:04 +0200902 lut_tensor = lut.create_lut_tensor(op.name + "_values", lut_values, DataType.int8)
Louis Verhaardf03bad32020-09-25 08:30:44 +0200903 op.set_activation_lut(lut_tensor)
Patrik Gustavssonc509d332020-12-22 13:53:52 +0100904 op.set_ifm_ofm_shapes()
Louis Verhaardf03bad32020-09-25 08:30:44 +0200905 return op
906
907
Louis Verhaard2e186c72020-10-09 10:47:04 +0200908def convert_to_lut8(op, fn, fn_name):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200909 # Converts op to a no-op + int8/uint8 LUT which is generated with the given function.
910 # fn is a function(real) -> real
Louis Verhaardaee5d752020-09-30 09:01:52 +0200911 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardf03bad32020-09-25 08:30:44 +0200912 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
913 return op
914 # Generate the LUT
915 ifm_scale = np.double(ifm.quantization.scale_f32)
916 ofm_scale = np.double(ofm.quantization.scale_f32)
917 zp_in = ifm.quantization.zero_point
918 zp_out = ofm.quantization.zero_point
919 values = []
920 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
921 quantized_min = min(ix)
922 quantized_max = max(ix)
923 for x in ix:
924 x_real = ifm_scale * (x - zp_in)
925 y_real = fn(x_real)
926 lut_result = round_away_zero(zp_out + y_real / ofm_scale)
927 lut_result = min(quantized_max, max(quantized_min, lut_result))
928 values.append(lut_result)
Louis Verhaard2e186c72020-10-09 10:47:04 +0200929 return convert_to_lut(op, values, fn_name)
Louis Verhaardf03bad32020-09-25 08:30:44 +0200930
931
932def convert_lrelu_to_lut(op, arch):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200933 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200934 # Generate the LUT
Louis Verhaardd7911c42020-08-25 13:36:41 +0200935 alpha = op.attrs["alpha"]
936 ifm_scale = np.double(ifm.quantization.scale_f32)
937 ofm_scale = np.double(ofm.quantization.scale_f32)
938 zp_in = ifm.quantization.zero_point
939 zp_out = ofm.quantization.zero_point
940 identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale)
941 alpha_scalar = 1
942 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale)
943 if "alpha_scaling" in op.attrs:
944 # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu
945 alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"]
946 values = []
Louis Verhaard58520b92020-08-24 16:45:38 +0200947 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200948 quantized_min = min(ix)
949 quantized_max = max(ix)
950 for x in ix:
951 if x < zp_in:
952 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(
953 alpha_scalar * (x - zp_in), alpha_scale, alpha_shift
954 )
955 else:
956 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift)
957 lut_result = min(quantized_max, max(quantized_min, lut_result))
958 values.append(lut_result)
Louis Verhaard2e186c72020-10-09 10:47:04 +0200959 return convert_to_lut(op, values, "lrelu")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200960
961
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200962def convert_lrelu(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200963 # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200964 if op.type != Op.LeakyRelu:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200965 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200966 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100967 if ifm is None or ofm is None:
968 return op
Louis Verhaardd7911c42020-08-25 13:36:41 +0200969 if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype:
970 # use LUT for int8/uint8
971 return convert_lrelu_to_lut(op, arch)
Tim Hall93582962020-09-09 21:58:15 +0100972 if check_quantized_tens_scaling_equal(ifm, ofm) and ifm.dtype == ofm.dtype == DataType.int16:
Louis Verhaardd7911c42020-08-25 13:36:41 +0200973 # use LeakyRelu unmodified for int16 with equal input/output scaling
974 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200975 return convert_lrelu_to_mul_max(op, arch)
976
977
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200978def convert_tanh_sigmoid_to_lut(op, arch, nng):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200979 # Converts int8/uint8 Sigmoid and Tanh to a LUT based solution
Louis Verhaardaee5d752020-09-30 09:01:52 +0200980 if op.type == Op.Sigmoid:
Louis Verhaard2e186c72020-10-09 10:47:04 +0200981 return convert_to_lut8(op, clamp_sigmoid, "sigmoid")
Louis Verhaardaee5d752020-09-30 09:01:52 +0200982 elif op.type == Op.Tanh:
Louis Verhaard2e186c72020-10-09 10:47:04 +0200983 return convert_to_lut8(op, math.tanh, "tanh")
Louis Verhaardf03bad32020-09-25 08:30:44 +0200984 return op
985
986
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100987def remove_reshapes(op, arch):
988 if op.run_on_npu and op.type == Op.Reshape:
989 ofm = op.ofm
990 ifm = op.ifm
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200991
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100992 # Check if quantization is the same in the input and output for the reshape ops
993 if not check_quantized_tens_scaling_equal(ifm, ofm):
994 # TODO Both tensors are needed, since quantisation properties currently are linked to Tensors.
995 # In order to remove this reshape either quantization properties need to be moved to Operator,
996 # or the reshape need to be replace with a NOP.
997 return
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200998
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100999 # Check if ifm is a sg input
1000 if ifm.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const):
1001 # put the reshape on CPU
1002 op.run_on_npu = False
1003 return
1004
1005 # Check if Reshape ifm/ofm are network ifm/ofm
1006 ifm_is_sg_ofm = any(ifm_cons is None for ifm_cons in ifm.consumer_list)
1007 ofm_is_sg_ofm = any(ofm_cons is None for ofm_cons in ofm.consumer_list)
1008
1009 if ifm_is_sg_ofm and ofm_is_sg_ofm:
1010 # Both ifm and ofm are sg outputs,add reshape to the ifm and put it on CPU
1011 ifm_cons_list_copy = ifm.consumer_list.copy()
1012 ifm_ops_copy = ifm.ops.copy()
1013 for ifm_cons in ifm_cons_list_copy:
1014 if ifm_cons is None:
1015 # Create a reshape op with ifm as output
1016 name = ifm.name + "_cpu_reshape"
1017 reshape_ifm = ifm.clone()
1018 reshape_op = Operation(Op.Reshape, name)
1019 reshape_op.attrs["new_shape"] = ifm.shape
1020 reshape_op.add_input_tensor(reshape_ifm)
1021 reshape_op.add_input_tensor(create_const_tensor(name + "_shape", [1], DataType.int32, ifm.shape))
1022 reshape_op.set_output_tensor(ifm)
1023 reshape_op.set_ifm_ofm_shapes()
1024 reshape_op.run_on_npu = False
1025 reshape_op.ofm.ops = [reshape_op]
1026 reshape_op.ofm.consumer_list = [None]
1027
1028 # Set reshape_ifm producers
1029 for prev_op in ifm_ops_copy:
1030 prev_op.outputs = [reshape_ifm]
1031 reshape_ifm.ops.append(prev_op)
1032
1033 # Set reshape_ifm consumers
1034 for ifm_cons in ifm_cons_list_copy:
1035 if ifm_cons is not None:
1036 for ifm_idx, cons_ifm in enumerate(ifm_cons.inputs):
1037 if cons_ifm == ifm:
1038 ifm_cons.set_input_tensor(reshape_ifm, ifm_idx)
1039
1040 ifm = reshape_ifm
1041 break
1042 ifm_is_sg_ofm = False
1043
1044 if ofm_is_sg_ofm:
1045 # Bypassed by replacing ifm with ofm
1046 ofm.ops = []
1047 for prev_op in ifm.ops:
1048 prev_op.outputs = [ofm]
1049 ofm.ops.append(prev_op)
1050
1051 # All ifm consumers need to use ofm as input
1052 for ifm_cons in ifm.consumer_list:
1053 for ifm_idx, cons_ifm in enumerate(ifm_cons.inputs):
1054 if cons_ifm == ifm:
1055 ifm_cons.set_input_tensor(ofm, ifm_idx)
1056 if op.ifm_shapes[0] != op.ofm_shapes[0]:
1057 ofm.avoid_NHCWB16 = True
1058 else:
1059 # Bypassed Reshape by replacing ofm with ifm
1060 for cons in ofm.consumer_list:
1061 for ifm_idx, cons_ifm in enumerate(cons.inputs):
1062 if cons_ifm == ofm:
1063 cons.set_input_tensor(ifm, ifm_idx)
1064 if op.ifm_shapes[0] != op.ofm_shapes[0]:
1065 ifm.avoid_NHCWB16 = True
1066
1067
1068def check_reshapes(op, arch):
1069 if op.run_on_npu and op.type == Op.Reshape:
1070 ofm = op.ofm
1071
1072 if check_quantized_tens_scaling_equal(op.ifm, ofm):
1073 # Reshape should have been removed
1074 raise VelaError(f"Reshape op {op} expected to have been removed, still remains")
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001075
1076
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001077def fuse_activation_function_with_prev(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001078 # if op is a no-op: attempts to move the activation function to the preceding op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001079 if not op.attrs.get("is_nop", False) or op.activation is None:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001080 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001081 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +01001082 if ifm is None or ofm is None:
1083 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001084 # finds the input(s) to the operation
1085 prev_op = ifm.ops[0]
1086 # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed
1087 fuse = (
1088 prev_op.run_on_npu
Louis Verhaardaee5d752020-09-30 09:01:52 +02001089 and prev_op.type.npu_block_type != NpuBlockType.Default
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001090 and len(ifm.ops) == 1
1091 and len(prev_op.outputs[0].consumers()) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +02001092 and prev_op.activation is None
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001093 )
1094 if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0:
1095 # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC),
1096 # LUT currently only works correctly for elementwise ops
1097 fuse = False
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001098 if not fuse:
1099 return op
1100 # Move the fused activation function + corresponding info to prev_op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001101 prev_op.activation = op.activation
1102 prev_op.forced_output_quantization = op.forced_output_quantization
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001103 if op.activation_lut is not None:
1104 prev_op.set_activation_lut(op.activation_lut)
1105 # Bypass op
Louis Verhaard98a34992020-09-01 10:39:04 +02001106 prev_op.set_output_tensor(ofm)
Tim Halle6ccd872020-11-09 16:46:37 +00001107 DebugDatabase.add_optimised(op, prev_op)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001108 return op
1109
1110
Louis Verhaardae2d5532020-12-11 17:19:54 +01001111def optimise_pad(op, arch, nng):
1112 """
1113 Converts tens1 -> PAD -> tens2 -> CONV to tens1 -> CONV
1114 if both operations can be run on the NPU.
1115 """
1116 if (
1117 (op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op())
1118 and op.run_on_npu
1119 and op.attrs["padding"] == Padding.VALID
1120 ):
1121 pad_op = op.ifm.ops[0]
1122 if pad_op.type != Op.Pad or not pad_op.run_on_npu:
1123 return op
1124 # Bypass the PAD operator
1125 op.set_input_tensor(pad_op.ifm, 0)
1126 # Adjust the padding attributes of the convolution operator
1127 op.attrs["padding"] = Padding.EXPLICIT
1128 padding = pad_op.inputs[1].values # 4x2 tensor, first dimension is N, H, W, C
1129 top, left, bottom, right = (padding[1][0], padding[2][0], padding[1][1], padding[2][1])
1130 op.attrs["explicit_padding"] = (top, left, bottom, right)
1131 op.set_ifm_ofm_shapes()
1132 return op
1133
1134
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001135def add_attrs_to_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001136 if op.type == Op.ResizeBilinear and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +02001137 input_tensor = op.inputs[0]
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001138 input_shape = op.ifm_shapes[0]
1139 upscaled_height = input_shape.height * 2
1140 upscaled_width = input_shape.width * 2
1141 out_shape = op.ofm_shapes[0]
1142 if not op.attrs["align_corners"] and out_shape.height == upscaled_height and out_shape.width == upscaled_width:
Dwight Lidman42fed942020-05-29 09:37:03 +02001143 # this means the output is supposed to be a x2 upscale,
1144 # so we need to do SAME padding
Michael McGeagh16895482020-12-14 15:51:20 +00001145 op.attrs["padding"] = Padding.SAME
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001146 elif (
1147 op.attrs["align_corners"]
1148 and out_shape.height == (upscaled_height - 1)
1149 and out_shape.width == (upscaled_width - 1)
1150 ):
Dwight Lidman42fed942020-05-29 09:37:03 +02001151 # here we can just run the avg pool without padding and
1152 # produce a (M * 2 - 1, N * 2 - 1) sized output
Michael McGeagh16895482020-12-14 15:51:20 +00001153 op.attrs["padding"] = Padding.VALID
Dwight Lidman42fed942020-05-29 09:37:03 +02001154 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +02001155 return op
Dwight Lidman42fed942020-05-29 09:37:03 +02001156 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +01001157 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +02001158 return op
1159
1160
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001161def fixup_bias_tensors(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001162 if op.type.needs_bias() and op.bias is None:
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001163 # Op has no bias, add bias tensor filled with zeros
1164 nr_biases = op.inputs[1].shape[-1]
1165 bias_values = [0] * nr_biases
1166 bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values)
1167 bias_tensor.quant_values = bias_tensor.values
1168 op.set_input_tensor(bias_tensor, -1)
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +02001169
1170 return op
1171
1172
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001173def supported_operator_check(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +01001174 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
1175 return op
1176
1177
Tim Halle6ccd872020-11-09 16:46:37 +00001178def _record_optimised(op, arch):
1179 if op.type != Op.Const:
1180 DebugDatabase.add_optimised(op, op)
1181
1182
Tim Hall79d07d22020-04-27 18:20:16 +01001183def optimise_graph_a(nng, arch, verbose_graph=False):
1184 if verbose_graph:
1185 nng.print_graph()
1186
Patrik Gustavsson2349d422020-12-01 16:02:29 +01001187 pre_process_list = [
1188 supported_operator_check,
1189 set_ifm_ofm_op_shapes,
1190 # TODO: memory-only Op removal
1191 ]
1192
1193 for idx, sg in enumerate(nng.subgraphs):
1194 # rewrite graph pass
1195 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1196 nng, sg, arch, [], pre_process_list, rewrite_unsupported=False,
1197 )
1198
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001199 # Handle Concat Ops
1200 for idx, sg in enumerate(nng.subgraphs):
1201 # rewrite graph pass
1202 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1203 nng, sg, arch, [], [rewrite_concat_ops], rewrite_unsupported=False,
1204 )
1205
1206 # Handle Split Ops
1207 for idx, sg in enumerate(nng.subgraphs):
1208 # rewrite graph pass
1209 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1210 nng,
1211 sg,
1212 arch,
1213 [],
1214 [rewrite_unpack_output, rewrite_stridedslice_output, convert_nop_split_to_identity],
1215 rewrite_unsupported=False,
1216 )
1217
1218 for idx, sg in enumerate(nng.subgraphs):
1219 # rewrite graph pass
1220 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1221 nng, sg, arch, [rewrite_split_ops], [], rewrite_unsupported=False,
1222 )
1223
1224 # Removal of reshapes
1225 for sg in nng.subgraphs:
1226 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [remove_reshapes])
1227 sg.refresh_after_modification()
1228
Tim Hall79d07d22020-04-27 18:20:16 +01001229 op_rewrite_list = [
Tim Hall4e127762020-05-15 16:05:49 +01001230 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +01001231 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +01001232 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +02001233 convert_softmax,
Diqing Zhong016b8272020-12-16 16:46:06 +01001234 optimise_strided_conv,
Diqing Zhong94457b12020-12-09 15:22:40 +01001235 convert_batched_fc_shape,
Tim Hall79d07d22020-04-27 18:20:16 +01001236 fixup_conv2d_backprop,
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +01001237 fixup_relus_with_differing_ifm_ofm_scaling,
Tim Hall79d07d22020-04-27 18:20:16 +01001238 fixup_act_reorder,
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001239 fixup_elementwise_with_scalars, # TODO Move to early stage?
Jacob Bohline843d332020-06-23 12:12:56 +02001240 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +02001241 fixup_resizebilinear,
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001242 fixup_bias_tensors,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001243 convert_mul_max_to_abs_or_lrelu,
1244 convert_lrelu,
Louis Verhaardf03bad32020-09-25 08:30:44 +02001245 convert_tanh_sigmoid_to_lut,
Tim Hall79d07d22020-04-27 18:20:16 +01001246 ]
1247
1248 for idx, sg in enumerate(nng.subgraphs):
1249 # rewrite graph pass
1250 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Dwight Lidman73320a42020-11-05 10:34:41 +01001251 nng, sg, arch, [], op_rewrite_list, rewrite_unsupported=False,
Tim Hall79d07d22020-04-27 18:20:16 +01001252 )
1253
1254 for idx, sg in enumerate(nng.subgraphs):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001255 # remove passthrough tensors and attempt further optimizations
1256 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Louis Verhaardae2d5532020-12-11 17:19:54 +01001257 nng,
1258 sg,
1259 arch,
1260 [remove_passthrough_tensor],
1261 [fuse_activation_function_with_prev, optimise_pad, add_padding_fields],
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001262 )
Tim Hall79d07d22020-04-27 18:20:16 +01001263
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001264 # Post-optimisation operator debug tracing, and checking that no undesired reshapes are left in the graph
Tim Halle6ccd872020-11-09 16:46:37 +00001265 for sg in nng.subgraphs:
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001266 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [check_reshapes, _record_optimised])
Tim Hall79d07d22020-04-27 18:20:16 +01001267
1268 if verbose_graph:
1269 nng.print_graph()
1270 return nng