blob: 5c1b90bd1758ec71c54d64c5a9db532d91472bff [file] [log] [blame]
Louis Verhaardebf4af62021-01-27 15:57:57 +01001# Copyright (C) 2020-2021 Arm Limited or its affiliates. All rights reserved.
Tim Hall79d07d22020-04-27 18:20:16 +01002#
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the License); you may
6# not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an AS IS BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
Tim Hall79d07d22020-04-27 18:20:16 +010016# Description:
17# Early optimisation of the network graph, using the rewrite_graph module to do the traversal of the graph. These are
18# split into two parts optimise_graph_a and optimise_graph_b.
Tim Hall79d07d22020-04-27 18:20:16 +010019import math
Diqing Zhong016b8272020-12-16 16:46:06 +010020import uuid
Louis Verhaardebf4af62021-01-27 15:57:57 +010021from typing import Tuple
Diego Russoea6111a2020-04-14 18:41:58 +010022
23import numpy as np
24
Louis Verhaardd7911c42020-08-25 13:36:41 +020025from . import fp_math
Louis Verhaardb9fc33c2020-08-13 11:47:36 +020026from . import lut
Diego Russoea6111a2020-04-14 18:41:58 +010027from . import rewrite_graph
Louis Verhaardd7911c42020-08-25 13:36:41 +020028from . import scaling
Diego Russoea6111a2020-04-14 18:41:58 +010029from .data_type import DataType
Tim Halle6ccd872020-11-09 16:46:37 +000030from .debug_database import DebugDatabase
Louis Verhaard7db78962020-05-25 15:05:26 +020031from .errors import UnsupportedFeatureError
Patrik Gustavsson3a269202021-01-21 08:28:55 +010032from .errors import VelaError
Dwight Lidman42fed942020-05-29 09:37:03 +020033from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Louis Verhaard8912c532020-09-30 12:11:49 +020034from .numeric_util import clamp_sigmoid
Louis Verhaarde0ef2732020-06-03 08:56:44 +020035from .numeric_util import full_shape
Louis Verhaardf03bad32020-09-25 08:30:44 +020036from .numeric_util import round_away_zero
Louis Verhaarde8a5a782020-11-02 18:04:27 +010037from .operation import create_activation_function
Diego Russoe8a10452020-04-21 17:39:10 +010038from .operation import NpuBlockType
Louis Verhaardaee5d752020-09-30 09:01:52 +020039from .operation import Op
Diego Russoe8a10452020-04-21 17:39:10 +010040from .operation import Operation
Michael McGeagh16895482020-12-14 15:51:20 +000041from .operation import Padding
Fredrik Svedbergd9c2c422020-12-01 16:33:45 +010042from .operation_util import create_avgpool_nop
patrik.gustavssoneeb85152020-12-21 17:10:40 +000043from .shape4d import Shape4D
Fredrik Svedberga0c36242020-06-03 15:43:31 +020044from .softmax import SoftMax
Tim Hall93582962020-09-09 21:58:15 +010045from .tensor import check_quantized_tens_scaling_equal
Michael McGeaghc5b549b2020-08-07 11:54:28 +010046from .tensor import create_const_tensor
Charles Xu9a03fdf2020-07-02 15:12:40 +020047from .tensor import QuantizationParameters
Diego Russoe8a10452020-04-21 17:39:10 +010048from .tensor import Tensor
Michael McGeagh7a6f8432020-12-02 15:29:22 +000049from .tflite_mapping import optype_to_builtintype
Tim Hall79d07d22020-04-27 18:20:16 +010050
Michael McGeaghf3e3ad72020-12-02 12:39:03 +000051passthrough_nodes = (Op.Identity,)
Tim Hall79d07d22020-04-27 18:20:16 +010052
Michael McGeaghf3e3ad72020-12-02 12:39:03 +000053memory_only_ops = (Op.Reshape,)
Michael McGeagh11b0bdb2020-09-08 11:07:35 +010054
Tim Hall79d07d22020-04-27 18:20:16 +010055
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +020056def remove_passthrough_tensor(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +010057 if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes:
58 assert len(tens.ops[0].inputs) == 1
59 tens = tens.ops[0].inputs[0]
60 return tens
61
62
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +010063def rewrite_concat_ops(op, arch):
Patrik Gustavsson3a269202021-01-21 08:28:55 +010064 if not op.run_on_npu or not op.type.is_concat_op():
65 return op
Tim Hall79d07d22020-04-27 18:20:16 +010066
Patrik Gustavsson3a269202021-01-21 08:28:55 +010067 axis_4D = 0
68 ofm = op.ofm
69 ofm.ops = []
70 offset = 0
Tim Hall79d07d22020-04-27 18:20:16 +010071
Patrik Gustavsson7bada402021-01-28 15:46:21 +010072 unfuse_activation_function(op)
73
Patrik Gustavsson3a269202021-01-21 08:28:55 +010074 if op.type == Op.Pack:
75 # Pack is also referred to as Stack
76 axis = int(op.attrs["axis"])
77 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +010078
Patrik Gustavsson3a269202021-01-21 08:28:55 +010079 if axis >= 0:
80 axis_4D = axis + (4 - len(desired_shape))
81 else:
82 axis_4D = axis
83
84 for idx, inp in enumerate(op.inputs):
85 op.ifm_shapes[idx] = Shape4D(desired_shape)
86 if Shape4D(inp.shape) != op.ifm_shapes[idx]:
87 inp.avoid_NHCWB16 = True
88 op.type = Op.PackReshaped
89
90 inputs, axis = op.get_concat_inputs_axis()
91
92 for idx, inp in enumerate(inputs):
93 if op.type != Op.PackReshaped:
94 op.ifm_shapes[idx] = Shape4D(inp.shape)
Patrik Gustavsson3d737172020-12-22 10:40:51 +010095 if axis >= 0:
96 axis_4D = axis + (4 - len(inp.shape))
97 else:
98 axis_4D = axis
Patrik Gustavsson3a269202021-01-21 08:28:55 +010099 new_op = Operation(Op.ConcatSliceWrite, op.name + str(idx))
100 new_op.inputs = [inp]
101 new_op.outputs = [ofm]
102 new_op.attrs["concat_axis"] = axis_4D
103 new_op.attrs["concat_start"] = offset
Tim Hall73e843f2021-02-04 22:47:46 +0000104 offset += op.ifm_shapes[idx][axis_4D]
Tim Hall79d07d22020-04-27 18:20:16 +0100105
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100106 new_op.attrs["concat_end"] = offset
107 new_op.run_on_npu = True
108 ofm.ops.append(new_op)
109 DebugDatabase.add_optimised(op, new_op)
Tim Hall73e843f2021-02-04 22:47:46 +0000110 new_op.ifm_shapes.append(op.ifm_shapes[idx])
111 new_op.ofm_shapes.append(op.ofm_shapes[0])
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100112 assert ofm.shape[axis] == offset
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200113
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100114 # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a
115 # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte
116 # aligned. For other values of axis the address offsets will be 16 byte aligned, as they are all based on c = 0
117 # and those addresses are always 16 byte aligned due to the NHCWB16 format.
118 if axis == -1 or axis == (len(ofm.shape) - 1):
119 for op in ofm.ops:
120 if op.attrs["concat_start"] % 16 != 0:
121 ofm.avoid_NHCWB16 = True
122 break
123 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100124
125
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100126def rewrite_split_ops(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100127
Patrik Gustavsson224e99b2021-01-14 10:55:43 +0100128 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 +0100129 split_op = tens.ops[0]
130
131 # Not supported so leave it and run on CPU
132 if not split_op.run_on_npu:
133 return tens
134
135 inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis()
136
137 tens.ops = []
Louis Verhaardaee5d752020-09-30 09:01:52 +0200138 new_op = Operation(Op.SplitSliceRead, split_op.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100139 new_op.inputs = [inp]
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100140 ofm_shape_idx = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100141
142 # For Split the offset cannot be extracted from the tensor so it has to
143 # be calculated from the index of the output tensor
Diego Russoea6111a2020-04-14 18:41:58 +0100144 if axis is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100145 # Get the start and end of the split
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100146 offset_start = [0] * 4
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100147 axis_4D_list = split_op.attrs.get("split_axis_4D", None) # Present for UnpackReshaped and some StridedSlice
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100148 for idx, out in enumerate(outputs):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100149 if axis_4D_list is not None:
150 axis_4D = axis_4D_list[idx]
Patrik Gustavsson3d737172020-12-22 10:40:51 +0100151 else:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100152 split_op.ofm_shapes[idx] = Shape4D(out.shape)
153 if axis >= 0:
154 axis_4D = axis + (4 - len(out.shape))
155 else:
156 axis_4D = axis
157
158 if out == tens:
159 ofm_shape_idx = idx
160 break
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000161
Tim Hall73e843f2021-02-04 22:47:46 +0000162 offset_start[axis_4D] += split_op.ofm_shapes[idx][axis_4D]
Tim Hall79d07d22020-04-27 18:20:16 +0100163
Patrik Gustavssoneebb1c22020-08-18 15:03:04 +0200164 # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input
165 if (offset_start[-1] % 16) != 0:
166 inp.avoid_NHCWB16 = True
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100167 else:
168 offset_start = full_shape(4, offset_start, 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100169
170 new_op.attrs["split_start"] = offset_start
Tim Hall79d07d22020-04-27 18:20:16 +0100171 new_op.run_on_npu = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100172 new_op.set_output_tensor(tens)
Patrik Gustavsson224e99b2021-01-14 10:55:43 +0100173 new_op.ifm_shapes.append(Shape4D(inp.shape))
Tim Hall73e843f2021-02-04 22:47:46 +0000174 new_op.ofm_shapes.append(split_op.ofm_shapes[ofm_shape_idx])
Tim Halle6ccd872020-11-09 16:46:37 +0000175 DebugDatabase.add_optimised(split_op, new_op)
Tim Hall79d07d22020-04-27 18:20:16 +0100176
177 return tens
178
179
180def needed_total_padding(input_size, stride, filter_size):
181 out_size = (input_size + stride - 1) // stride
182 needed_input = (out_size - 1) * stride + filter_size
183 total_padding = max(0, needed_input - input_size)
184 return total_padding
185
186
Louis Verhaardebf4af62021-01-27 15:57:57 +0100187def calc_explicit_padding(input_size, stride, filter_size, pad_before, pad_after) -> Tuple[int, int]:
188 """
189 Based on explicit padding provided in a PAD operation, returns the corresponding hardware padding
190 that provides equivalent results.
191 """
192 total_padding = needed_total_padding(input_size, stride, filter_size)
193 # The top/left padding can be taken as is from the PAD
194 output_pad_before = pad_before
195 # The bottom/right padding might need downward adjustment depending on stride/input size
196 output_pad_after = pad_after
197 while output_pad_after > 0 and output_pad_after % stride != (total_padding - pad_before) % stride:
198 output_pad_after -= 1
199 return output_pad_before, output_pad_after
200
201
202def calc_padding_and_skirt(padding_type, kernel, input_shape, explicit_padding):
203 k_w, k_h = kernel.dilated_wh()
204 s_x, s_y = kernel.stride
205 ypad = needed_total_padding(int(input_shape.height), int(s_y), int(k_h))
206 xpad = needed_total_padding(int(input_shape.width), int(s_x), int(k_w))
Michael McGeagh16895482020-12-14 15:51:20 +0000207 if padding_type == Padding.SAME:
Tim Hall79d07d22020-04-27 18:20:16 +0100208 left_pad = (xpad + 0) // 2
209 right_pad = (xpad + 1) // 2
210 top_pad = (ypad + 0) // 2
211 bottom_pad = (ypad + 1) // 2
Michael McGeagh16895482020-12-14 15:51:20 +0000212 elif padding_type == Padding.VALID:
Tim Hall79d07d22020-04-27 18:20:16 +0100213 left_pad = 0
214 right_pad = 0
215 top_pad = 0
216 bottom_pad = 0
Louis Verhaardae2d5532020-12-11 17:19:54 +0100217 elif padding_type == Padding.EXPLICIT:
218 # Padding is specified in a PAD operator which has been bypassed.
Louis Verhaardebf4af62021-01-27 15:57:57 +0100219 top, left, bottom, right = explicit_padding
220 top_pad, bottom_pad = calc_explicit_padding(int(input_shape.height), int(s_y), int(k_h), int(top), int(bottom))
221 left_pad, right_pad = calc_explicit_padding(int(input_shape.width), int(s_x), int(k_w), int(left), int(right))
Tim Hall79d07d22020-04-27 18:20:16 +0100222 else:
Michael McGeagh16895482020-12-14 15:51:20 +0000223 raise UnsupportedFeatureError(f"Unknown padding")
Tim Hall79d07d22020-04-27 18:20:16 +0100224 padding = (top_pad, left_pad, bottom_pad, right_pad)
225 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
226 return padding, skirt
227
Tim Hallc30f4952020-06-15 20:47:35 +0100228
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100229def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_shape, upscaling_factor):
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200230 kernel_height, kernel_width = kernel_size[0], kernel_size[1]
Michael McGeagh16895482020-12-14 15:51:20 +0000231 if padding_type == Padding.SAME:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100232 ypad = needed_total_padding(int(input_shape.height) * upscaling_factor, int(stride[1]), int(kernel_height))
233 xpad = needed_total_padding(int(input_shape.width) * upscaling_factor, int(stride[2]), int(kernel_width))
Jacob Bohlind47cc272020-08-24 11:42:14 +0200234 right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0)
235 bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200236 left_pad = max(kernel_width - 1 - right_pad, 0)
237 top_pad = max(kernel_height - 1 - bottom_pad, 0)
Michael McGeagh16895482020-12-14 15:51:20 +0000238 elif padding_type == Padding.VALID:
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200239 right_pad = max(kernel_width - 2, 0)
240 bottom_pad = max(kernel_height - 2, 0)
241 left_pad = kernel_width - 1
242 top_pad = kernel_height - 1
Jacob Bohlincf7da102020-05-20 09:03:40 +0200243 else:
Michael McGeagh16895482020-12-14 15:51:20 +0000244 raise UnsupportedFeatureError(f"Unknown padding")
Jacob Bohlincf7da102020-05-20 09:03:40 +0200245 padding = (top_pad, left_pad, bottom_pad, right_pad)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200246 skirt = padding
Jacob Bohlincf7da102020-05-20 09:03:40 +0200247 return padding, skirt
248
Tim Hall79d07d22020-04-27 18:20:16 +0100249
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200250def fixup_conv2d_backprop(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200251 if op.type == Op.Conv2DBackpropInput:
Tim Hall79d07d22020-04-27 18:20:16 +0100252 # flip the inputs
253 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200254 op.type = Op.Conv2DBackpropInputSwitchedBias
Louis Verhaard69b84802020-12-16 12:02:28 +0100255 op.ifm.resampling_mode = resampling_mode.TRANSPOSE
Jacob Bohlincf7da102020-05-20 09:03:40 +0200256
257 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100258 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100259
260 return op
261
262
Charles Xu9a03fdf2020-07-02 15:12:40 +0200263# Convert the op to an elementwise add
264def convert_resizebilinear_1x1_to_add(op):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200265 op.type = Op.Add
Charles Xu9a03fdf2020-07-02 15:12:40 +0200266 op.name = op.name + "_add"
Charles Xu9a03fdf2020-07-02 15:12:40 +0200267 op.attrs["resizebilinear"] = True
268 # Create an input tensor filled with zeros
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100269 shape = op.ofm_shapes[0].as_list()
Charles Xu9a03fdf2020-07-02 15:12:40 +0200270 tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add")
271 tens.values = np.zeros(shape)
272 tens.quant_values = np.zeros(shape, np.uint8)
273 tens.quantization = QuantizationParameters(0.0, 255.0)
274 tens.quantization.scale_f32 = 1.0
275 tens.quantization.zero_point = 0
276 tens.consumer_list = [op]
277 tens_op = op.inputs[1].ops[0]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100278 tens_op.set_output_tensor(tens)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200279 # Set the add inputs
280 op.inputs[1] = op.inputs[0]
281 op.inputs[0] = tens
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000282 op.set_ifm_ofm_shapes()
Charles Xu9a03fdf2020-07-02 15:12:40 +0200283
284 return op
285
286
Charles Xu87c13502020-08-06 12:17:26 +0200287# Convert ResizeBilinear to a number of 2x2 pool ops
288def convert_resizebilinear_to_2x2_pool(op):
289 count = 0
290 pre_op = op
291 outputs = op.outputs
292
293 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
294 if op.attrs["align_corners"]:
295 shape_modifier = 1
Michael McGeagh16895482020-12-14 15:51:20 +0000296 op.attrs["padding"] = Padding.VALID
Charles Xu87c13502020-08-06 12:17:26 +0200297 else:
298 shape_modifier = 0
Michael McGeagh16895482020-12-14 15:51:20 +0000299 op.attrs["padding"] = Padding.SAME
Charles Xu87c13502020-08-06 12:17:26 +0200300 op.inputs[0].resampling_mode = resampling_mode.NEAREST
301
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100302 upscaled_shape = np.array(op.ifm_shapes[0].get_hw_as_list())
303 out_shape = np.array(op.ofm_shapes[0].get_hw_as_list())
Charles Xu87c13502020-08-06 12:17:26 +0200304 if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all():
305 return op
306
307 while (upscaled_shape < out_shape).all():
308 if count == 0:
309 scaled_op = pre_op
310 else:
311 scaled_op = op.clone("_{}".format(count))
312 scaled_op.inputs[0] = pre_op.outputs[0]
313
314 upscaled_shape = upscaled_shape * 2 - shape_modifier
315
316 if (upscaled_shape == out_shape).all():
317 scaled_op.outputs = outputs
318 scaled_op.outputs[0].ops = [scaled_op]
319 else:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100320 shape = op.ofm_shapes[0].as_list()
321 shape[1:3] = upscaled_shape
Charles Xu87c13502020-08-06 12:17:26 +0200322 out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count))
323 out_tens.quantization = op.outputs[0].quantization.clone()
324 out_tens.quantization.quant_min = np.iinfo(np.int16).min
325 out_tens.quantization.quant_max = np.iinfo(np.int16).max
326 scaled_op.set_output_tensor(out_tens)
327 pre_op = scaled_op
328 count += 1
329
330 # Setup the scale value
331 if scaled_op.inputs[0].dtype.bits == 8 and scaled_op.outputs[0].dtype.bits == 16:
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100332 scaled_op.rescale = 128
Charles Xu87c13502020-08-06 12:17:26 +0200333 elif scaled_op.inputs[0].dtype.bits == 16 and scaled_op.outputs[0].dtype.bits == 8:
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100334 scaled_op.rescale = 1 / 128
335 else:
336 scaled_op.rescale = None
Patrik Gustavssoncc6915c2020-12-22 09:16:50 +0100337 scaled_op.set_ifm_ofm_shapes()
Charles Xu87c13502020-08-06 12:17:26 +0200338
339 return op
340
341
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200342def fixup_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200343 if op.type == Op.ResizeBilinear and op.run_on_npu:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100344 if op.ifm_shapes[0] == op.ofm_shapes[0]:
Charles Xu36ffaf32020-08-05 15:40:44 +0200345 # Bypass nop resizebilinear
346 op.inputs = op.inputs[:1]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200347 op.type = Op.Identity
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100348 elif op.ifm_shapes[0].height == 1 and op.ifm_shapes[0].width == 1:
Charles Xu87c13502020-08-06 12:17:26 +0200349 convert_resizebilinear_1x1_to_add(op)
350 else:
351 convert_resizebilinear_to_2x2_pool(op)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200352
353 return op
354
355
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200356def convert_nop_split_to_identity(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200357 if op.type == Op.Split and op.attrs.get("num_splits") == 1:
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200358 # the list comprehension should return a list with a single tensor
359 # if it shouldn't, remove_passthrough_tensor will fail appropriately
360 op.inputs = [i for i in op.inputs if i.shape == op.outputs[0].shape]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200361 op.type = Op.Identity
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200362 return op
363
364
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100365def rewrite_fully_connected_input(op, arch, nng):
366 if op.type == Op.FullyConnected:
367 n_in_elems = op.weights.shape[-2]
368 elms = op.ifm.elements()
369 batch_size = elms // n_in_elems
370 assert batch_size * n_in_elems == elms
371
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100372 op.ifm_shapes[0] = Shape4D([batch_size, 1, 1, n_in_elems])
Patrik Gustavssonda2b0032021-02-04 16:28:29 +0100373 if Shape4D(op.ifm.shape) != op.ifm_shapes[0]:
374 op.ifm.avoid_NHCWB16 = True
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100375 return op
376
377
Diqing Zhong94457b12020-12-09 15:22:40 +0100378def convert_batched_fc_shape(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200379 if op.type == Op.FullyConnected:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100380 # Check if the first dimension indicates batching
381 if op.ifm_shapes[0].batch > 1:
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200382 batching_split = {4: (2, 2), 8: (2, 4), 16: (4, 4)}
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100383 n = op.ifm_shapes[0].batch
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200384 h, w = batching_split.get(n, (1, n))
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100385 op.ifm_shapes[0] = Shape4D([1, h, w, op.ifm_shapes[0].depth])
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200386
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100387 op.ifm.avoid_NHCWB16 = True
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200388
389 # Reshape Weights to be 4D. IO becomes HWIO
390 weight_tensor = op.inputs[1]
391 weight_tensor.quant_values = np.expand_dims(np.expand_dims(weight_tensor.quant_values, axis=0), axis=0)
392 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
393
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100394 n = op.ofm_shapes[0].batch
395 h, w = batching_split.get(n, (1, n))
396 op.ofm_shapes[0] = Shape4D([1, h, w, op.ofm_shapes[0].depth])
397 op.ofm.avoid_NHCWB16 = True
Tim Hall79d07d22020-04-27 18:20:16 +0100398 return op
399
400
Patrik Gustavsson7bada402021-01-28 15:46:21 +0100401def unfuse_activation_function(op):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200402 if op.type == Op.ConcatTFLite and op.run_on_npu and op.activation is not None:
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100403 act_op = Operation(op.activation.op_type, op.name + op.activation.op_type.name)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200404 op.activation = None
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200405 out_tens = op.outputs[0]
406 intermediate_tens = out_tens.clone("_act_intermediate")
407 act_op.set_output_tensor(out_tens)
408 act_op.add_input_tensor(intermediate_tens)
409 op.set_output_tensor(intermediate_tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000410 act_op.set_ifm_ofm_shapes()
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200411
Louis Verhaard8912c532020-09-30 12:11:49 +0200412
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100413def rewrite_stridedslice_output(op, arch, nng):
414 if not op.run_on_npu or op.type != Op.StridedSlice:
415 return op
416
417 new_axis_mask = op.attrs["new_axis_mask"]
418 shrink_axis_mask = op.attrs["shrink_axis_mask"]
419
420 if shrink_axis_mask == 0 and new_axis_mask == 0:
421 return op
422
423 axis_4D = [0] * len(op.outputs)
424 for idx, out_tens in enumerate(op.outputs):
425 output_shape = list(out_tens.shape)
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))
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100435 output_shape = output_shape[:axis] + [1] + output_shape[axis:]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100436
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100437 assert len(out_tens.shape) == (len(op.inputs[0].shape) - n)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100438 op.attrs["shrink_axis_mask"] = 0
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100439 if axis >= 0:
440 axis_4D[idx] = axis + (4 - len(output_shape))
441 else:
442 axis_4D[idx] = axis
443 op.ofm_shapes[idx] = Shape4D(output_shape)
444
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100445 elif new_axis_mask != 0:
446 n = 0
447 axis = 0
448 while new_axis_mask:
449 prev_mask = new_axis_mask
450 n += 1
451 new_axis_mask &= new_axis_mask - 1
452 axis = int(math.log2(prev_mask - new_axis_mask))
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100453 output_shape = output_shape[:axis] + output_shape[(axis + 1) :]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100454 new_axis_mask >>= 1
455
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100456 assert len(out_tens.shape) == (len(op.inputs[0].shape) + n)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100457 op.attrs["new_axis_mask"] = 0
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100458 if axis >= 0:
459 axis_4D[idx] = axis + (4 - len(output_shape))
460 else:
461 axis_4D[idx] = axis
462 op.ofm_shapes[idx] = Shape4D(output_shape)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100463
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100464 if op.ofm_shapes[idx] != Shape4D(out_tens.shape):
465 out_tens.avoid_NHCWB16 = True
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100466
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100467 op.attrs["split_axis_4D"] = axis_4D
468 return op
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100469
470
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100471def rewrite_unpack_output(op, arch, nng):
472 tens = op.outputs[0]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100473 if op.run_on_npu and op.type == Op.Unpack:
Tim Hall79d07d22020-04-27 18:20:16 +0100474 # Unpack is also referred to as Unstack
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100475 axis = int(op.attrs["axis"])
476 op.type = Op.UnpackReshaped
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100477 desired_output_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100478
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100479 if axis >= 0:
480 axis_4D = axis + (4 - len(desired_output_shape))
481 else:
482 axis_4D = axis
Tim Hall79d07d22020-04-27 18:20:16 +0100483
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100484 axis_4D_list = [0] * len(op.outputs)
Tim Hall79d07d22020-04-27 18:20:16 +0100485 for idx, out_tens in enumerate(op.outputs):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100486 op.ofm_shapes[idx] = Shape4D(desired_output_shape)
487 axis_4D_list[idx] = axis_4D
488 if op.ofm_shapes[idx] != Shape4D(out_tens.shape):
489 out_tens.avoid_NHCWB16 = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100490
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100491 op.attrs["split_axis_4D"] = axis_4D_list
492 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100493
494
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200495def add_padding_fields(op, arch, nng):
Jacob Bohlin90033f32020-08-28 15:45:44 +0200496 if op.run_on_npu:
497 if "padding" in op.attrs:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100498 input_shape = op.ifm_shapes[0]
499 output_shape = op.ofm_shapes[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200500 if op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op():
Jacob Bohlin90033f32020-08-28 15:45:44 +0200501 kernel_size = op.inputs[1].shape[:2]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200502 elif op.type.is_pool_op() or op.type.npu_block_type == NpuBlockType.ReduceSum:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200503 kernel_size = op.attrs["ksize"][1:3]
Jacob Bohlin90033f32020-08-28 15:45:44 +0200504 else:
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000505 raise UnsupportedFeatureError(f"Unknown operation that uses padding: {optype_to_builtintype(op.type)}")
Tim Hall79d07d22020-04-27 18:20:16 +0100506
Louis Verhaardaee5d752020-09-30 09:01:52 +0200507 if op.type == Op.Conv2DBackpropInputSwitchedBias:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100508 upscaling_factor = output_shape.height // input_shape.height
Jacob Bohlin90033f32020-08-28 15:45:44 +0200509 padding, skirt = calc_upscaled_padding_and_skirt(
510 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
511 )
512 else:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200513 padding, skirt = calc_padding_and_skirt(
Louis Verhaardebf4af62021-01-27 15:57:57 +0100514 op.attrs["padding"], op.kernel, input_shape, op.attrs.get("explicit_padding"),
Jacob Bohlin90033f32020-08-28 15:45:44 +0200515 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200516
Jacob Bohlin90033f32020-08-28 15:45:44 +0200517 op.attrs["explicit_padding"] = padding
518 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200519
Tim Hall79d07d22020-04-27 18:20:16 +0100520 return op
521
522
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200523def convert_depthwise_to_conv(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100524 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
525 # the ofm depth equals the depth multipler.
526 # If those conditions are true, then we can perform a simple
527 # switch of the operator type (and weight order)
528
Louis Verhaardaee5d752020-09-30 09:01:52 +0200529 if op.type == Op.DepthwiseConv2DBias and (op.attrs["depth_multiplier"] != 1):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100530 ifm_shape = op.ifm_shapes[0]
Tim Hall79d07d22020-04-27 18:20:16 +0100531 weight_tensor = op.inputs[1]
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100532 ofm_shape = op.ofm_shapes[0]
533 if (ifm_shape.depth == 1) and (ofm_shape.depth == op.attrs["depth_multiplier"]):
Tim Hall79d07d22020-04-27 18:20:16 +0100534 # Change op type to Conv2d
Louis Verhaardaee5d752020-09-30 09:01:52 +0200535 op.type = Op.Conv2DBias
Tim Hall79d07d22020-04-27 18:20:16 +0100536 del op.attrs["channel_multiplier"]
537 del op.attrs["depth_multiplier"]
538
539 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100540 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100541 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200542 raise UnsupportedFeatureError(
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000543 f"Unsupported 'DEPTHWISE_CONV_2D' with depth_multiplier = {op.attrs['depth_multiplier']},",
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100544 f" ifm channels = {ifm_shape.depth}, ofm channels = {ofm_shape.depth}",
Tim Hall79d07d22020-04-27 18:20:16 +0100545 )
Tim Halle6ccd872020-11-09 16:46:37 +0000546 DebugDatabase.add_optimised(op, op)
Tim Hall79d07d22020-04-27 18:20:16 +0100547 return op
548
549
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200550def reorder_depthwise_weights(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200551 if op.type.is_depthwise_conv2d_op():
Jacob Bohline843d332020-06-23 12:12:56 +0200552 weight_tensor = op.inputs[1]
553 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100554 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200555 weight_tensor.weight_transpose_depthwise = True
556
557 return op
558
559
Diqing Zhong016b8272020-12-16 16:46:06 +0100560def optimise_strided_conv(op, arch, nng):
561 stride_x, stride_y = op.get_kernel_stride()
562 ifm_tensor, _, weight_tensor, _ = op.get_ifm_ifm2_weights_ofm()
563
564 if (
565 op.type == Op.Conv2DBias
566 and op.op_index == 0
567 and stride_x == 2
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100568 and op.ifm_shapes[0].depth <= 4
569 and op.ifm_shapes[0].width % 2 == 0
Diqing Zhong016b8272020-12-16 16:46:06 +0100570 and weight_tensor is not None
571 and weight_tensor.shape[1] >= 2
572 ):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100573 ifm_shape = op.ifm_shapes[0]
Diqing Zhong016b8272020-12-16 16:46:06 +0100574 # IFM
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100575 op.ifm_shapes[0] = Shape4D([ifm_shape.batch, ifm_shape.height, ifm_shape.width // 2, ifm_shape.depth * 2])
576 op.ifm.avoid_NHCWB16 = True
Diqing Zhong016b8272020-12-16 16:46:06 +0100577
578 # Weights
579 weight_shape = weight_tensor.shape
580 if weight_shape[1] % 2 != 0:
581 weight_shape[1] = weight_shape[1] + 1
582 padded_array = np.zeros(weight_shape)
583 for i in range(weight_shape[0]):
584 padded_array[i] = np.vstack(
585 [
586 weight_tensor.quant_values[i],
587 np.full((1, weight_shape[2], weight_shape[3]), weight_tensor.quantization.zero_point),
588 ]
589 )
590 weight_tensor.quant_values = padded_array
591 weight_shape[1] //= 2
592 weight_shape[2] *= 2
593 weight_tensor.quant_values = np.reshape(weight_tensor.quant_values, weight_shape)
594 weight_tensor.set_all_shapes(weight_shape)
595 # If multiple copies of the weights are used, we could avoid
596 # them having the same address by changing the value_id
597 weight_tensor.value_id = uuid.uuid4()
598
599 # Strides
600 stride_x = 1
601 op.attrs.update({"stride_w": stride_x, "stride_h": stride_y, "strides": (1, stride_y, stride_x, 1)})
602
Diqing Zhong016b8272020-12-16 16:46:06 +0100603 return op
604
605
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200606def convert_conv_to_fc(op, arch, nng):
Michael McGeagh8d939c02020-07-29 13:11:43 +0100607 # Conv 1x1 can be equivalent to Fully Connected.
608 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
609 # caching/double buffering for the weights.
610 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200611 if op.type == Op.Conv2DBias:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000612 h = op.ifm_shapes[0].height
613 w = op.ifm_shapes[0].width
Michael McGeagh8d939c02020-07-29 13:11:43 +0100614 kh, kw, _, _ = op.inputs[1].shape
615 if h == 1 and w == 1 and kh == 1 and kw == 1:
616 # Overwrite this op as a Fully Connected Op
617 op.name += "_fc"
Louis Verhaardaee5d752020-09-30 09:01:52 +0200618 op.type = Op.FullyConnected
Michael McGeagh8d939c02020-07-29 13:11:43 +0100619 op.attrs = {
Michael McGeagh8d939c02020-07-29 13:11:43 +0100620 "weights_format": 0,
Michael McGeagh8d939c02020-07-29 13:11:43 +0100621 }
622 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
623 weight_tensor = op.inputs[1]
624 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
625 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100626
Tim Halle6ccd872020-11-09 16:46:37 +0000627 DebugDatabase.add_optimised(op, op)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100628 return op
629
630
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200631def fixup_relus_with_differing_ifm_ofm_scaling(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200632 if op.run_on_npu and op.type.is_relu_op():
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100633 ifm = op.inputs[0]
634 ofm = op.outputs[0]
635 # Relu with differing IFM and OFM scaling cannot be fused with another primary op
636 # and requires its own to be inserted
Tim Hall93582962020-09-09 21:58:15 +0100637 if not check_quantized_tens_scaling_equal(ifm, ofm):
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100638 # Override this op with its own primary op (avgpool)
639 relu_fused_op = create_avgpool_nop(op.name + "_avgpool")
640 # And fuse the original activation function to it
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100641 relu_fused_op.activation = create_activation_function(op.type)
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100642 # Tidy up and assign the ifm and ofm to the new op
643 ifm.consumer_list.remove(op)
Andreas Nevalainenf3d737e2020-09-25 14:12:43 +0200644
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100645 relu_fused_op.add_input_tensor(ifm)
646 relu_fused_op.set_output_tensor(ofm)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000647 relu_fused_op.set_ifm_ofm_shapes()
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100648 op = relu_fused_op
649 return op
650
651
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200652def fixup_elementwise_with_scalars(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200653 if op.type.is_binary_elementwise_op():
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200654 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200655 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
656 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
657 if diff > 0:
658 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
659 elif diff < 0:
660 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200661 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
662 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
663 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
664 ifm_tensor.storage_shape = ifm_tensor.shape
665 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
666 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
667 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
668 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200669 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100670
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200671
Tim Hall4e127762020-05-15 16:05:49 +0100672# Set input/output tensor equivalence to the same id for memory operations
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200673def set_tensor_equivalence(op, arch, nng):
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100674 if op.type in memory_only_ops:
Tim Hall4e127762020-05-15 16:05:49 +0100675 eid = op.outputs[0].equivalence_id
676 for inp in op.inputs:
677 inp.equivalence_id = eid
678 return op
679
680
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100681def set_ifm_ofm_op_shapes(op, arch, nng):
682 if op.run_on_npu and op.type.needs_shapes():
683 if op.ifm_shapes or op.ofm_shapes:
684 # Shapes already set
685 return op
686 op.set_ifm_ofm_shapes()
687 return op
688
689
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200690def convert_softmax(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200691 if op.type == Op.Softmax and op.run_on_npu:
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200692 softmax = SoftMax(op)
693 op = softmax.get_graph()
694 return op
695
696
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200697def convert_mul_max_to_abs_or_lrelu(op, arch, nng):
Diego Russoea6111a2020-04-14 18:41:58 +0100698 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100699
700 Input X For X = -1 or X > 0
701 | \ / This subgraph can be replaced with either
702 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
703 | /
704 Max
705 """
706
Louis Verhaardaee5d752020-09-30 09:01:52 +0200707 if op.type == Op.Maximum:
Tim Hall79d07d22020-04-27 18:20:16 +0100708 # finds the Mul input(s) to the Max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200709 muls = [i for i in op.inputs if i.ops[0].type == Op.Mul]
Tim Hall79d07d22020-04-27 18:20:16 +0100710 if len(muls) == 1:
711 mul = muls[0].ops[0]
712 elif len(muls) == 2:
713 # In the case both inputs are Muls, find the one with the same input as the Max
714 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
715 else:
716 # No Mul inputs
717 return op
718
719 # make sure the Mul doesn't have any other consumers
Louis Verhaardd7911c42020-08-25 13:36:41 +0200720 mul_ofm = mul.outputs[0]
721 if len(mul_ofm.consumers()) != 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100722 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200723 # make sure the Mul doesn't have a fused activation function
724 if mul.activation:
Tim Hall79d07d22020-04-27 18:20:16 +0100725 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200726 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100727 if ifm is None or ofm is None:
728 return op
729
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200730 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
731 return op
Tim Hall93582962020-09-09 21:58:15 +0100732 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 +0200733 # rewrite to LeakyRelu currently only makes sense if the quantization is identical
734 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100735
736 # finds the branched input that goes to both the Max and the Mul
737 shared = set(op.inputs) & set(mul.inputs)
738 if len(shared) == 1:
739 shared_in = shared.pop()
740 # find the constant scalar input to the Mul
741 const_tens = (set(mul.inputs) - {shared_in}).pop()
742 # check that it is a scalar
743 if const_tens.shape != []:
744 return op
745 const = const_tens.ops[0]
746 # check that it is a constant
Louis Verhaardaee5d752020-09-30 09:01:52 +0200747 if const.type != Op.Const:
Tim Hall79d07d22020-04-27 18:20:16 +0100748 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200749 # Remove the Mul from the shared input's consumers
750 shared_in.consumer_list.remove(mul)
Tim Hall79d07d22020-04-27 18:20:16 +0100751 else:
752 return op
753
754 val = const.outputs[0].values
755 if val >= 0:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200756 new_op = Op.LeakyRelu
Tim Hall79d07d22020-04-27 18:20:16 +0100757 op.attrs["alpha"] = val
Louis Verhaardd7911c42020-08-25 13:36:41 +0200758 # to produce bit exact results, the alpha is not enough;
759 # save additional scaling info in attr "alpha_scale", to be used as input
760 # to the LUT construction
761 alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point
762 mul_ifm_scale = np.double(ifm.quantization.scale_f32)
763 mul_ifm2_scale = np.double(const_tens.quantization.scale_f32)
764 mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32)
765 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale)
766 op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift)
Tim Hall79d07d22020-04-27 18:20:16 +0100767 elif val == -1:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200768 new_op = Op.Abs
Tim Hall79d07d22020-04-27 18:20:16 +0100769 else:
770 return op
771
Louis Verhaardaee5d752020-09-30 09:01:52 +0200772 op.type = new_op
773 op.name = op.name.replace("Maximum", new_op.name)
774 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100775 op.inputs = [shared_in]
Patrik Gustavssonc509d332020-12-22 13:53:52 +0100776 op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000777
778 # Record optimisation in debug database
779 DebugDatabase.add_optimised(op, op)
780
Tim Hall79d07d22020-04-27 18:20:16 +0100781 return op
782
783
Diqing Zhong189f7482021-01-26 12:12:51 +0100784def convert_hardswish_to_lut(op, arch, nng):
785 if op.type == Op.HardSwish:
786 ifm, ofm = op.get_ifm_ofm()
787 # Generate the LUT
788 ifm_scale = np.double(ifm.quantization.scale_f32)
789 ofm_scale = np.double(ofm.quantization.scale_f32)
790 zp_in = ifm.quantization.zero_point
791 zp_out = ofm.quantization.zero_point
792 ifm_scale_hires = (1 / 128) * ifm_scale
793 relu_multiplier = np.double(3 / 32768)
794 out_scale, out_shift = scaling.quantise_scale(ifm_scale_hires / ofm_scale)
795 relu_scale, relu_shift = scaling.quantise_scale(ifm_scale_hires / relu_multiplier)
796 # Use 16bit scale
797 out_scale_16 = fp_math.downscale_multiplier_int32_to_int16(out_scale)
798 relu_scale_16 = fp_math.downscale_multiplier_int32_to_int16(relu_scale)
799
800 values = []
801 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
802 quantized_min = min(ix)
803 quantized_max = max(ix)
804 for x in ix:
805 input_value = x - zp_in
806 input_value_hires = input_value * 128
807 # Compute the input value on essentially the output scale, not shifted yet
808 input_value_preshift = fp_math.saturating_rounding_mul16(input_value_hires, out_scale_16)
809 # Compute the "relu-ish multiplier". This matches the code in TensorFlow Lite Micro kernel
810 relu_value = np.int16(input_value_hires)
811 if relu_shift < 31:
812 relu_value = fp_math.shift_left16(relu_value, 30 - relu_shift)
813
814 relu_value = fp_math.saturating_rounding_mul16(relu_value, relu_scale_16)
815
816 if relu_shift < 31:
817 relu_value = fp_math.shift_left16(relu_value, 1)
818
819 if relu_shift > 31:
820 relu_value = fp_math.rounding_divide_by_pot(relu_value, relu_shift - 31)
821
822 # Rescaled the value into a 16bit fixedpoint relu_value in [-1, 1]
823 # Now convert that to a 16bit fixedpoint value in [0, 1]
824 relu_value = (relu_value + (1 << 15)) >> 1
825 lut_result = fp_math.saturating_mul16(relu_value, input_value_preshift)
826 shift = 31 - out_shift
827 shift = -shift if shift < 0 else 0
828 # Finally apply the output shift
829 lut_result = fp_math.rounding_divide_by_pot(lut_result, shift) + zp_out
830 lut_result = min(quantized_max, max(quantized_min, lut_result))
831 values.append(lut_result)
832 return convert_to_lut(op, values, "hardswish")
833 return op
834
835
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200836def convert_lrelu_to_mul_max(op, arch):
837 # Converts LeakyRelu to Max(alpha * IFM, identity * IFM)
838 # (the opposite of convert_mul_max_to_abs_or_lrelu)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200839 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100840 if ifm is None or ofm is None:
841 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200842
843 # Add multiplication with alpha
Louis Verhaardaee5d752020-09-30 09:01:52 +0200844 mul_alpha = Operation(Op.Mul, op.name + "_mul_alpha")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200845 mul_alpha.add_input_tensor(ifm)
846 # Create const tensor containing alpha as scalar
847 alpha = op.attrs["alpha"]
848 quantization = ifm.quantization.clone()
849 quantization.min = 0
850 quantization.max = alpha * (quantization.quant_max - quantization.quant_min)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200851 quantization.zero_point = 0
Louis Verhaardece4e652021-01-07 13:35:47 +0100852 if np.isinf(1 / np.float32(alpha)):
853 # Handling of alpha near zero
854 quantization.scale_f32 = 1
855 scalar = 0
856 else:
857 quantization.scale_f32 = alpha
858 scalar = 1
859 alpha_tens = create_const_tensor(
860 op.name + "_alpha_scalar", [], ifm.dtype, [scalar], np.int8, quantization=quantization
861 )
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200862 mul_alpha.add_input_tensor(alpha_tens)
863 fm_alpha = ofm.clone(op.name + "_alpha")
864 mul_alpha.set_output_tensor(fm_alpha)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000865 mul_alpha.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000866 DebugDatabase.add_optimised(op, mul_alpha)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200867
Tim Hall93582962020-09-09 21:58:15 +0100868 if check_quantized_tens_scaling_equal(ifm, ofm):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200869 # No identity multiplication is needed
870 fm_id = ifm
871 else:
872 # Add multiplication with identity
Louis Verhaardaee5d752020-09-30 09:01:52 +0200873 mul_identity = Operation(Op.Mul, op.name + "_mul_identity")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200874 mul_identity.add_input_tensor(ifm)
875 # Create const tensor containing identity as scalar
876 quantization = ifm.quantization.clone()
877 quantization.min = 0
878 quantization.max = quantization.quant_max - quantization.quant_min
879 quantization.scale_f32 = 1
880 quantization.zero_point = 0
881 identity_tens = create_const_tensor(
882 op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization
883 )
884 mul_identity.add_input_tensor(identity_tens)
Louis Verhaardece4e652021-01-07 13:35:47 +0100885 # Make sure that fm_id is allocated to a different address than fm_alpha
886 fm_id = ofm.clone(op.name + "_id", set_unique=True)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200887 mul_identity.set_output_tensor(fm_id)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000888 mul_identity.set_ifm_ofm_shapes()
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100889 DebugDatabase.add_optimised(op, mul_identity)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200890
891 # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs
Louis Verhaardaee5d752020-09-30 09:01:52 +0200892 op.type = Op.Maximum
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200893 op.name = op.name.replace("LeakyRelu", "Maximum")
894 op.inputs = []
895 ifm.consumer_list.remove(op)
896 op.add_input_tensor(fm_alpha)
897 op.add_input_tensor(fm_id)
Patrik Gustavssonc509d332020-12-22 13:53:52 +0100898 op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000899
900 DebugDatabase.add_optimised(op, op)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200901 return op
902
903
Louis Verhaard2e186c72020-10-09 10:47:04 +0200904def convert_to_lut(op, lut_values, lut_name):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200905 # Rewrite the operation by Add with scalar 0 + LUT activation
906 ifm = op.inputs[0]
Tim Hall93582962020-09-09 21:58:15 +0100907 if ifm is None:
908 return op
Louis Verhaard58520b92020-08-24 16:45:38 +0200909 assert ifm.dtype.size_in_bytes() == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +0200910 op.type = Op.Add
Louis Verhaard2e186c72020-10-09 10:47:04 +0200911 op.name = op.name + "_lut_" + lut_name
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200912 # Mark as no-op to enable potential fusing optimizations
913 op.attrs["is_nop"] = True
914 # Create an input tensor containing scalar zero
915 quantization = QuantizationParameters(0.0, 255.0)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200916 quantization.scale_f32 = ifm.quantization.scale_f32
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200917 quantization.zero_point = 0
Louis Verhaard2e186c72020-10-09 10:47:04 +0200918 tens = create_const_tensor(op.inputs[0].name + "_scalar0", [], ifm.dtype, [0], np.uint8, quantization=quantization)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200919 op.add_input_tensor(tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000920 op.ifm_shapes.append(Shape4D(tens.shape))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100921
Louis Verhaardf03bad32020-09-25 08:30:44 +0200922 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
923 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
924 # should be the same as the IFM
Louis Verhaardaee5d752020-09-30 09:01:52 +0200925 op.forced_output_quantization = ifm.quantization
Louis Verhaard2e186c72020-10-09 10:47:04 +0200926 lut_tensor = lut.create_lut_tensor(op.name + "_values", lut_values, DataType.int8)
Louis Verhaardf03bad32020-09-25 08:30:44 +0200927 op.set_activation_lut(lut_tensor)
Patrik Gustavssonc509d332020-12-22 13:53:52 +0100928 op.set_ifm_ofm_shapes()
Louis Verhaardf03bad32020-09-25 08:30:44 +0200929 return op
930
931
Louis Verhaard2e186c72020-10-09 10:47:04 +0200932def convert_to_lut8(op, fn, fn_name):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200933 # Converts op to a no-op + int8/uint8 LUT which is generated with the given function.
934 # fn is a function(real) -> real
Louis Verhaardaee5d752020-09-30 09:01:52 +0200935 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardf03bad32020-09-25 08:30:44 +0200936 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
937 return op
938 # Generate the LUT
939 ifm_scale = np.double(ifm.quantization.scale_f32)
940 ofm_scale = np.double(ofm.quantization.scale_f32)
941 zp_in = ifm.quantization.zero_point
942 zp_out = ofm.quantization.zero_point
943 values = []
944 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
945 quantized_min = min(ix)
946 quantized_max = max(ix)
947 for x in ix:
948 x_real = ifm_scale * (x - zp_in)
949 y_real = fn(x_real)
950 lut_result = round_away_zero(zp_out + y_real / ofm_scale)
951 lut_result = min(quantized_max, max(quantized_min, lut_result))
952 values.append(lut_result)
Louis Verhaard2e186c72020-10-09 10:47:04 +0200953 return convert_to_lut(op, values, fn_name)
Louis Verhaardf03bad32020-09-25 08:30:44 +0200954
955
956def convert_lrelu_to_lut(op, arch):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200957 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200958 # Generate the LUT
Louis Verhaardd7911c42020-08-25 13:36:41 +0200959 alpha = op.attrs["alpha"]
960 ifm_scale = np.double(ifm.quantization.scale_f32)
961 ofm_scale = np.double(ofm.quantization.scale_f32)
962 zp_in = ifm.quantization.zero_point
963 zp_out = ofm.quantization.zero_point
964 identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale)
965 alpha_scalar = 1
966 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale)
967 if "alpha_scaling" in op.attrs:
968 # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu
969 alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"]
970 values = []
Louis Verhaard58520b92020-08-24 16:45:38 +0200971 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200972 quantized_min = min(ix)
973 quantized_max = max(ix)
974 for x in ix:
975 if x < zp_in:
976 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(
977 alpha_scalar * (x - zp_in), alpha_scale, alpha_shift
978 )
979 else:
980 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift)
981 lut_result = min(quantized_max, max(quantized_min, lut_result))
982 values.append(lut_result)
Louis Verhaard2e186c72020-10-09 10:47:04 +0200983 return convert_to_lut(op, values, "lrelu")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200984
985
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200986def convert_lrelu(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200987 # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200988 if op.type != Op.LeakyRelu:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200989 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200990 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100991 if ifm is None or ofm is None:
992 return op
Louis Verhaardd7911c42020-08-25 13:36:41 +0200993 if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype:
994 # use LUT for int8/uint8
995 return convert_lrelu_to_lut(op, arch)
Tim Hall93582962020-09-09 21:58:15 +0100996 if check_quantized_tens_scaling_equal(ifm, ofm) and ifm.dtype == ofm.dtype == DataType.int16:
Louis Verhaardd7911c42020-08-25 13:36:41 +0200997 # use LeakyRelu unmodified for int16 with equal input/output scaling
998 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200999 return convert_lrelu_to_mul_max(op, arch)
1000
1001
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001002def convert_tanh_sigmoid_to_lut(op, arch, nng):
Louis Verhaardf03bad32020-09-25 08:30:44 +02001003 # Converts int8/uint8 Sigmoid and Tanh to a LUT based solution
Louis Verhaardaee5d752020-09-30 09:01:52 +02001004 if op.type == Op.Sigmoid:
Louis Verhaard2e186c72020-10-09 10:47:04 +02001005 return convert_to_lut8(op, clamp_sigmoid, "sigmoid")
Louis Verhaardaee5d752020-09-30 09:01:52 +02001006 elif op.type == Op.Tanh:
Louis Verhaard2e186c72020-10-09 10:47:04 +02001007 return convert_to_lut8(op, math.tanh, "tanh")
Louis Verhaardf03bad32020-09-25 08:30:44 +02001008 return op
1009
1010
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001011def remove_reshapes(op, arch):
1012 if op.run_on_npu and op.type == Op.Reshape:
1013 ofm = op.ofm
1014 ifm = op.ifm
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001015
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001016 # Check if quantization is the same in the input and output for the reshape ops
1017 if not check_quantized_tens_scaling_equal(ifm, ofm):
1018 # TODO Both tensors are needed, since quantisation properties currently are linked to Tensors.
1019 # In order to remove this reshape either quantization properties need to be moved to Operator,
1020 # or the reshape need to be replace with a NOP.
1021 return
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001022
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001023 # Check if ifm is a sg input
1024 if ifm.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const):
1025 # put the reshape on CPU
1026 op.run_on_npu = False
1027 return
1028
1029 # Check if Reshape ifm/ofm are network ifm/ofm
1030 ifm_is_sg_ofm = any(ifm_cons is None for ifm_cons in ifm.consumer_list)
1031 ofm_is_sg_ofm = any(ofm_cons is None for ofm_cons in ofm.consumer_list)
1032
1033 if ifm_is_sg_ofm and ofm_is_sg_ofm:
1034 # Both ifm and ofm are sg outputs,add reshape to the ifm and put it on CPU
1035 ifm_cons_list_copy = ifm.consumer_list.copy()
1036 ifm_ops_copy = ifm.ops.copy()
1037 for ifm_cons in ifm_cons_list_copy:
1038 if ifm_cons is None:
1039 # Create a reshape op with ifm as output
1040 name = ifm.name + "_cpu_reshape"
1041 reshape_ifm = ifm.clone()
1042 reshape_op = Operation(Op.Reshape, name)
1043 reshape_op.attrs["new_shape"] = ifm.shape
1044 reshape_op.add_input_tensor(reshape_ifm)
1045 reshape_op.add_input_tensor(create_const_tensor(name + "_shape", [1], DataType.int32, ifm.shape))
1046 reshape_op.set_output_tensor(ifm)
1047 reshape_op.set_ifm_ofm_shapes()
1048 reshape_op.run_on_npu = False
1049 reshape_op.ofm.ops = [reshape_op]
1050 reshape_op.ofm.consumer_list = [None]
1051
1052 # Set reshape_ifm producers
1053 for prev_op in ifm_ops_copy:
1054 prev_op.outputs = [reshape_ifm]
1055 reshape_ifm.ops.append(prev_op)
1056
1057 # Set reshape_ifm consumers
1058 for ifm_cons in ifm_cons_list_copy:
1059 if ifm_cons is not None:
1060 for ifm_idx, cons_ifm in enumerate(ifm_cons.inputs):
1061 if cons_ifm == ifm:
1062 ifm_cons.set_input_tensor(reshape_ifm, ifm_idx)
1063
1064 ifm = reshape_ifm
1065 break
1066 ifm_is_sg_ofm = False
1067
1068 if ofm_is_sg_ofm:
1069 # Bypassed by replacing ifm with ofm
1070 ofm.ops = []
1071 for prev_op in ifm.ops:
1072 prev_op.outputs = [ofm]
1073 ofm.ops.append(prev_op)
1074
1075 # All ifm consumers need to use ofm as input
1076 for ifm_cons in ifm.consumer_list:
1077 for ifm_idx, cons_ifm in enumerate(ifm_cons.inputs):
1078 if cons_ifm == ifm:
1079 ifm_cons.set_input_tensor(ofm, ifm_idx)
1080 if op.ifm_shapes[0] != op.ofm_shapes[0]:
1081 ofm.avoid_NHCWB16 = True
1082 else:
1083 # Bypassed Reshape by replacing ofm with ifm
1084 for cons in ofm.consumer_list:
1085 for ifm_idx, cons_ifm in enumerate(cons.inputs):
1086 if cons_ifm == ofm:
1087 cons.set_input_tensor(ifm, ifm_idx)
1088 if op.ifm_shapes[0] != op.ofm_shapes[0]:
1089 ifm.avoid_NHCWB16 = True
1090
1091
1092def check_reshapes(op, arch):
1093 if op.run_on_npu and op.type == Op.Reshape:
1094 ofm = op.ofm
1095
1096 if check_quantized_tens_scaling_equal(op.ifm, ofm):
1097 # Reshape should have been removed
1098 raise VelaError(f"Reshape op {op} expected to have been removed, still remains")
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001099
1100
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001101def fuse_activation_function_with_prev(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001102 # if op is a no-op: attempts to move the activation function to the preceding op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001103 if not op.attrs.get("is_nop", False) or op.activation is None:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001104 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001105 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +01001106 if ifm is None or ofm is None:
1107 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001108 # finds the input(s) to the operation
1109 prev_op = ifm.ops[0]
1110 # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed
1111 fuse = (
1112 prev_op.run_on_npu
Louis Verhaardaee5d752020-09-30 09:01:52 +02001113 and prev_op.type.npu_block_type != NpuBlockType.Default
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001114 and len(ifm.ops) == 1
1115 and len(prev_op.outputs[0].consumers()) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +02001116 and prev_op.activation is None
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001117 )
1118 if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0:
1119 # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC),
1120 # LUT currently only works correctly for elementwise ops
1121 fuse = False
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001122 if not fuse:
1123 return op
1124 # Move the fused activation function + corresponding info to prev_op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001125 prev_op.activation = op.activation
1126 prev_op.forced_output_quantization = op.forced_output_quantization
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001127 if op.activation_lut is not None:
1128 prev_op.set_activation_lut(op.activation_lut)
1129 # Bypass op
Louis Verhaard98a34992020-09-01 10:39:04 +02001130 prev_op.set_output_tensor(ofm)
Tim Halle6ccd872020-11-09 16:46:37 +00001131 DebugDatabase.add_optimised(op, prev_op)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001132 return op
1133
1134
Louis Verhaardae2d5532020-12-11 17:19:54 +01001135def optimise_pad(op, arch, nng):
1136 """
1137 Converts tens1 -> PAD -> tens2 -> CONV to tens1 -> CONV
1138 if both operations can be run on the NPU.
1139 """
1140 if (
1141 (op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op())
1142 and op.run_on_npu
1143 and op.attrs["padding"] == Padding.VALID
1144 ):
1145 pad_op = op.ifm.ops[0]
1146 if pad_op.type != Op.Pad or not pad_op.run_on_npu:
1147 return op
1148 # Bypass the PAD operator
1149 op.set_input_tensor(pad_op.ifm, 0)
1150 # Adjust the padding attributes of the convolution operator
1151 op.attrs["padding"] = Padding.EXPLICIT
1152 padding = pad_op.inputs[1].values # 4x2 tensor, first dimension is N, H, W, C
1153 top, left, bottom, right = (padding[1][0], padding[2][0], padding[1][1], padding[2][1])
1154 op.attrs["explicit_padding"] = (top, left, bottom, right)
1155 op.set_ifm_ofm_shapes()
1156 return op
1157
1158
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001159def add_attrs_to_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001160 if op.type == Op.ResizeBilinear and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +02001161 input_tensor = op.inputs[0]
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001162 input_shape = op.ifm_shapes[0]
1163 upscaled_height = input_shape.height * 2
1164 upscaled_width = input_shape.width * 2
1165 out_shape = op.ofm_shapes[0]
1166 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 +02001167 # this means the output is supposed to be a x2 upscale,
1168 # so we need to do SAME padding
Michael McGeagh16895482020-12-14 15:51:20 +00001169 op.attrs["padding"] = Padding.SAME
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001170 elif (
1171 op.attrs["align_corners"]
1172 and out_shape.height == (upscaled_height - 1)
1173 and out_shape.width == (upscaled_width - 1)
1174 ):
Dwight Lidman42fed942020-05-29 09:37:03 +02001175 # here we can just run the avg pool without padding and
1176 # produce a (M * 2 - 1, N * 2 - 1) sized output
Michael McGeagh16895482020-12-14 15:51:20 +00001177 op.attrs["padding"] = Padding.VALID
Dwight Lidman42fed942020-05-29 09:37:03 +02001178 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +02001179 return op
Dwight Lidman42fed942020-05-29 09:37:03 +02001180 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +01001181 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +02001182 return op
1183
1184
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001185def fixup_bias_tensors(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001186 if op.type.needs_bias() and op.bias is None:
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001187 # Op has no bias, add bias tensor filled with zeros
1188 nr_biases = op.inputs[1].shape[-1]
1189 bias_values = [0] * nr_biases
1190 bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values)
1191 bias_tensor.quant_values = bias_tensor.values
1192 op.set_input_tensor(bias_tensor, -1)
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +02001193
1194 return op
1195
1196
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001197def supported_operator_check(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +01001198 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
1199 return op
1200
1201
Tim Halle6ccd872020-11-09 16:46:37 +00001202def _record_optimised(op, arch):
1203 if op.type != Op.Const:
1204 DebugDatabase.add_optimised(op, op)
1205
1206
Tim Hall79d07d22020-04-27 18:20:16 +01001207def optimise_graph_a(nng, arch, verbose_graph=False):
1208 if verbose_graph:
1209 nng.print_graph()
1210
Patrik Gustavsson2349d422020-12-01 16:02:29 +01001211 pre_process_list = [
1212 supported_operator_check,
1213 set_ifm_ofm_op_shapes,
1214 # TODO: memory-only Op removal
1215 ]
1216
1217 for idx, sg in enumerate(nng.subgraphs):
1218 # rewrite graph pass
1219 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1220 nng, sg, arch, [], pre_process_list, rewrite_unsupported=False,
1221 )
1222
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001223 # Handle Concat Ops
1224 for idx, sg in enumerate(nng.subgraphs):
1225 # rewrite graph pass
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +01001226 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [rewrite_concat_ops])
1227 sg.refresh_after_modification()
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001228
1229 # Handle Split Ops
1230 for idx, sg in enumerate(nng.subgraphs):
1231 # rewrite graph pass
1232 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1233 nng,
1234 sg,
1235 arch,
1236 [],
1237 [rewrite_unpack_output, rewrite_stridedslice_output, convert_nop_split_to_identity],
1238 rewrite_unsupported=False,
1239 )
1240
1241 for idx, sg in enumerate(nng.subgraphs):
1242 # rewrite graph pass
1243 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1244 nng, sg, arch, [rewrite_split_ops], [], rewrite_unsupported=False,
1245 )
1246
1247 # Removal of reshapes
1248 for sg in nng.subgraphs:
1249 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [remove_reshapes])
1250 sg.refresh_after_modification()
1251
Tim Hall79d07d22020-04-27 18:20:16 +01001252 op_rewrite_list = [
Tim Hall4e127762020-05-15 16:05:49 +01001253 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +01001254 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +01001255 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +02001256 convert_softmax,
Diqing Zhong016b8272020-12-16 16:46:06 +01001257 optimise_strided_conv,
Diqing Zhong189f7482021-01-26 12:12:51 +01001258 convert_hardswish_to_lut,
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +01001259 rewrite_fully_connected_input,
Diqing Zhong94457b12020-12-09 15:22:40 +01001260 convert_batched_fc_shape,
Tim Hall79d07d22020-04-27 18:20:16 +01001261 fixup_conv2d_backprop,
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +01001262 fixup_relus_with_differing_ifm_ofm_scaling,
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001263 fixup_elementwise_with_scalars, # TODO Move to early stage?
Jacob Bohline843d332020-06-23 12:12:56 +02001264 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +02001265 fixup_resizebilinear,
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001266 fixup_bias_tensors,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001267 convert_mul_max_to_abs_or_lrelu,
1268 convert_lrelu,
Louis Verhaardf03bad32020-09-25 08:30:44 +02001269 convert_tanh_sigmoid_to_lut,
Tim Hall79d07d22020-04-27 18:20:16 +01001270 ]
1271
1272 for idx, sg in enumerate(nng.subgraphs):
1273 # rewrite graph pass
1274 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Dwight Lidman73320a42020-11-05 10:34:41 +01001275 nng, sg, arch, [], op_rewrite_list, rewrite_unsupported=False,
Tim Hall79d07d22020-04-27 18:20:16 +01001276 )
1277
1278 for idx, sg in enumerate(nng.subgraphs):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001279 # remove passthrough tensors and attempt further optimizations
1280 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Louis Verhaardae2d5532020-12-11 17:19:54 +01001281 nng,
1282 sg,
1283 arch,
1284 [remove_passthrough_tensor],
1285 [fuse_activation_function_with_prev, optimise_pad, add_padding_fields],
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001286 )
Tim Hall79d07d22020-04-27 18:20:16 +01001287
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001288 # Post-optimisation operator debug tracing, and checking that no undesired reshapes are left in the graph
Tim Halle6ccd872020-11-09 16:46:37 +00001289 for sg in nng.subgraphs:
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001290 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [check_reshapes, _record_optimised])
Tim Hall79d07d22020-04-27 18:20:16 +01001291
1292 if verbose_graph:
1293 nng.print_graph()
1294 return nng