blob: eb93106e3c4f9a8a53535e8a46e80425ed85954b [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 Gustavsson138d47f2021-02-08 10:13:48 +010099 avgpool_op = create_avgpool_nop(op.name + str(idx) + "_avgpool")
100 avgpool_op.inputs = [inp]
101 avgpool_op.outputs = [ofm]
102 avgpool_op.attrs["concat_axis"] = axis_4D
103 avgpool_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 Gustavsson138d47f2021-02-08 10:13:48 +0100106 avgpool_op.attrs["concat_end"] = offset
107 avgpool_op.run_on_npu = True
108 ofm.ops.append(avgpool_op)
109 DebugDatabase.add_optimised(op, avgpool_op)
110 avgpool_op.ifm_shapes.append(op.ifm_shapes[idx])
111 avgpool_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
Patrik Gustavsson138d47f2021-02-08 10:13:48 +0100180def insert_copy_op_after_tens(tens):
181 tens_cons_list_copy = tens.consumer_list.copy()
182
183 # Create a avg_pool nop op with ifm as input
184 copy_tens = tens.clone()
185 copy_op = create_avgpool_nop(tens.name + "_avgpool")
186 copy_op.add_input_tensor(tens)
187 copy_op.set_output_tensor(copy_tens)
188 copy_op.set_ifm_ofm_shapes()
189 copy_op.run_on_npu = True
190
191 # Set copy_ifm consumers
192 for tens_cons in tens_cons_list_copy:
193 if tens_cons is not None:
194 for ifm_idx, cons_inp in enumerate(tens_cons.inputs):
195 if cons_inp == tens:
196 tens_cons.set_input_tensor(copy_tens, ifm_idx)
197
198 DebugDatabase.add_optimised(tens.ops[0], copy_op)
199
200
201def fix_sg_input_output(op, arch, nng):
202 if not op.run_on_npu or op.type != Op.Reshape:
203 return op
204
205 # For the memory operators we want to remove, tensors are removed.
206 # But in order to to do this, they cannot be outputs of the sg,
207 # this need to be fixed prior to the removal.
208 # Solution is to add a avgpool NOP, to maintain the original tensor.
209
210 # Check if operator ifm/ofm are sg ifm/ofm
211 ifm_is_sg_ifm = op.ifm.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const)
212 ifm_is_sg_ofm = any(ifm_cons is None for ifm_cons in op.ifm.consumer_list)
213 ofm_is_sg_ofm = any(ofm_cons is None for ofm_cons in op.ofm.consumer_list)
214
215 if op.type == Op.Reshape and (ifm_is_sg_ofm or ifm_is_sg_ifm) and ofm_is_sg_ofm:
216 # Both ifm and ofm are sg outputs, only ifm need a copy, in order to remove the Reshape
217 insert_copy_op_after_tens(op.ifm)
218
219 return op
220
221
Tim Hall79d07d22020-04-27 18:20:16 +0100222def needed_total_padding(input_size, stride, filter_size):
223 out_size = (input_size + stride - 1) // stride
224 needed_input = (out_size - 1) * stride + filter_size
225 total_padding = max(0, needed_input - input_size)
226 return total_padding
227
228
Louis Verhaardebf4af62021-01-27 15:57:57 +0100229def calc_explicit_padding(input_size, stride, filter_size, pad_before, pad_after) -> Tuple[int, int]:
230 """
231 Based on explicit padding provided in a PAD operation, returns the corresponding hardware padding
232 that provides equivalent results.
233 """
234 total_padding = needed_total_padding(input_size, stride, filter_size)
235 # The top/left padding can be taken as is from the PAD
236 output_pad_before = pad_before
237 # The bottom/right padding might need downward adjustment depending on stride/input size
238 output_pad_after = pad_after
239 while output_pad_after > 0 and output_pad_after % stride != (total_padding - pad_before) % stride:
240 output_pad_after -= 1
241 return output_pad_before, output_pad_after
242
243
244def calc_padding_and_skirt(padding_type, kernel, input_shape, explicit_padding):
245 k_w, k_h = kernel.dilated_wh()
246 s_x, s_y = kernel.stride
247 ypad = needed_total_padding(int(input_shape.height), int(s_y), int(k_h))
248 xpad = needed_total_padding(int(input_shape.width), int(s_x), int(k_w))
Michael McGeagh16895482020-12-14 15:51:20 +0000249 if padding_type == Padding.SAME:
Tim Hall79d07d22020-04-27 18:20:16 +0100250 left_pad = (xpad + 0) // 2
251 right_pad = (xpad + 1) // 2
252 top_pad = (ypad + 0) // 2
253 bottom_pad = (ypad + 1) // 2
Michael McGeagh16895482020-12-14 15:51:20 +0000254 elif padding_type == Padding.VALID:
Tim Hall79d07d22020-04-27 18:20:16 +0100255 left_pad = 0
256 right_pad = 0
257 top_pad = 0
258 bottom_pad = 0
Louis Verhaardae2d5532020-12-11 17:19:54 +0100259 elif padding_type == Padding.EXPLICIT:
260 # Padding is specified in a PAD operator which has been bypassed.
Louis Verhaardebf4af62021-01-27 15:57:57 +0100261 top, left, bottom, right = explicit_padding
262 top_pad, bottom_pad = calc_explicit_padding(int(input_shape.height), int(s_y), int(k_h), int(top), int(bottom))
263 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 +0100264 else:
Michael McGeagh16895482020-12-14 15:51:20 +0000265 raise UnsupportedFeatureError(f"Unknown padding")
Tim Hall79d07d22020-04-27 18:20:16 +0100266 padding = (top_pad, left_pad, bottom_pad, right_pad)
267 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
268 return padding, skirt
269
Tim Hallc30f4952020-06-15 20:47:35 +0100270
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100271def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_shape, upscaling_factor):
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200272 kernel_height, kernel_width = kernel_size[0], kernel_size[1]
Michael McGeagh16895482020-12-14 15:51:20 +0000273 if padding_type == Padding.SAME:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100274 ypad = needed_total_padding(int(input_shape.height) * upscaling_factor, int(stride[1]), int(kernel_height))
275 xpad = needed_total_padding(int(input_shape.width) * upscaling_factor, int(stride[2]), int(kernel_width))
Jacob Bohlind47cc272020-08-24 11:42:14 +0200276 right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0)
277 bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200278 left_pad = max(kernel_width - 1 - right_pad, 0)
279 top_pad = max(kernel_height - 1 - bottom_pad, 0)
Michael McGeagh16895482020-12-14 15:51:20 +0000280 elif padding_type == Padding.VALID:
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200281 right_pad = max(kernel_width - 2, 0)
282 bottom_pad = max(kernel_height - 2, 0)
283 left_pad = kernel_width - 1
284 top_pad = kernel_height - 1
Jacob Bohlincf7da102020-05-20 09:03:40 +0200285 else:
Michael McGeagh16895482020-12-14 15:51:20 +0000286 raise UnsupportedFeatureError(f"Unknown padding")
Jacob Bohlincf7da102020-05-20 09:03:40 +0200287 padding = (top_pad, left_pad, bottom_pad, right_pad)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200288 skirt = padding
Jacob Bohlincf7da102020-05-20 09:03:40 +0200289 return padding, skirt
290
Tim Hall79d07d22020-04-27 18:20:16 +0100291
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200292def fixup_conv2d_backprop(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200293 if op.type == Op.Conv2DBackpropInput:
Tim Hall79d07d22020-04-27 18:20:16 +0100294 # flip the inputs
295 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200296 op.type = Op.Conv2DBackpropInputSwitchedBias
Louis Verhaard69b84802020-12-16 12:02:28 +0100297 op.ifm.resampling_mode = resampling_mode.TRANSPOSE
Jacob Bohlincf7da102020-05-20 09:03:40 +0200298
299 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100300 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100301
302 return op
303
304
Charles Xu9a03fdf2020-07-02 15:12:40 +0200305# Convert the op to an elementwise add
306def convert_resizebilinear_1x1_to_add(op):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200307 op.type = Op.Add
Charles Xu9a03fdf2020-07-02 15:12:40 +0200308 op.name = op.name + "_add"
Charles Xu9a03fdf2020-07-02 15:12:40 +0200309 op.attrs["resizebilinear"] = True
310 # Create an input tensor filled with zeros
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100311 shape = op.ofm_shapes[0].as_list()
Charles Xu9a03fdf2020-07-02 15:12:40 +0200312 tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add")
313 tens.values = np.zeros(shape)
314 tens.quant_values = np.zeros(shape, np.uint8)
315 tens.quantization = QuantizationParameters(0.0, 255.0)
316 tens.quantization.scale_f32 = 1.0
317 tens.quantization.zero_point = 0
318 tens.consumer_list = [op]
319 tens_op = op.inputs[1].ops[0]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100320 tens_op.set_output_tensor(tens)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200321 # Set the add inputs
322 op.inputs[1] = op.inputs[0]
323 op.inputs[0] = tens
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000324 op.set_ifm_ofm_shapes()
Charles Xu9a03fdf2020-07-02 15:12:40 +0200325
326 return op
327
328
Charles Xu87c13502020-08-06 12:17:26 +0200329# Convert ResizeBilinear to a number of 2x2 pool ops
330def convert_resizebilinear_to_2x2_pool(op):
331 count = 0
332 pre_op = op
333 outputs = op.outputs
334
335 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
336 if op.attrs["align_corners"]:
337 shape_modifier = 1
Michael McGeagh16895482020-12-14 15:51:20 +0000338 op.attrs["padding"] = Padding.VALID
Charles Xu87c13502020-08-06 12:17:26 +0200339 else:
340 shape_modifier = 0
Michael McGeagh16895482020-12-14 15:51:20 +0000341 op.attrs["padding"] = Padding.SAME
Charles Xu87c13502020-08-06 12:17:26 +0200342 op.inputs[0].resampling_mode = resampling_mode.NEAREST
343
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100344 upscaled_shape = np.array(op.ifm_shapes[0].get_hw_as_list())
345 out_shape = np.array(op.ofm_shapes[0].get_hw_as_list())
Charles Xu87c13502020-08-06 12:17:26 +0200346 if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all():
347 return op
348
349 while (upscaled_shape < out_shape).all():
350 if count == 0:
351 scaled_op = pre_op
352 else:
353 scaled_op = op.clone("_{}".format(count))
354 scaled_op.inputs[0] = pre_op.outputs[0]
355
356 upscaled_shape = upscaled_shape * 2 - shape_modifier
357
358 if (upscaled_shape == out_shape).all():
359 scaled_op.outputs = outputs
360 scaled_op.outputs[0].ops = [scaled_op]
361 else:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100362 shape = op.ofm_shapes[0].as_list()
363 shape[1:3] = upscaled_shape
Charles Xu87c13502020-08-06 12:17:26 +0200364 out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count))
365 out_tens.quantization = op.outputs[0].quantization.clone()
366 out_tens.quantization.quant_min = np.iinfo(np.int16).min
367 out_tens.quantization.quant_max = np.iinfo(np.int16).max
368 scaled_op.set_output_tensor(out_tens)
369 pre_op = scaled_op
370 count += 1
371
372 # Setup the scale value
373 if scaled_op.inputs[0].dtype.bits == 8 and scaled_op.outputs[0].dtype.bits == 16:
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100374 scaled_op.rescale = 128
Charles Xu87c13502020-08-06 12:17:26 +0200375 elif scaled_op.inputs[0].dtype.bits == 16 and scaled_op.outputs[0].dtype.bits == 8:
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100376 scaled_op.rescale = 1 / 128
377 else:
378 scaled_op.rescale = None
Patrik Gustavssoncc6915c2020-12-22 09:16:50 +0100379 scaled_op.set_ifm_ofm_shapes()
Charles Xu87c13502020-08-06 12:17:26 +0200380
381 return op
382
383
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200384def fixup_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200385 if op.type == Op.ResizeBilinear and op.run_on_npu:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100386 if op.ifm_shapes[0] == op.ofm_shapes[0]:
Charles Xu36ffaf32020-08-05 15:40:44 +0200387 # Bypass nop resizebilinear
388 op.inputs = op.inputs[:1]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200389 op.type = Op.Identity
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100390 elif op.ifm_shapes[0].height == 1 and op.ifm_shapes[0].width == 1:
Charles Xu87c13502020-08-06 12:17:26 +0200391 convert_resizebilinear_1x1_to_add(op)
392 else:
393 convert_resizebilinear_to_2x2_pool(op)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200394
395 return op
396
397
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200398def convert_nop_split_to_identity(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200399 if op.type == Op.Split and op.attrs.get("num_splits") == 1:
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200400 # the list comprehension should return a list with a single tensor
401 # if it shouldn't, remove_passthrough_tensor will fail appropriately
402 op.inputs = [i for i in op.inputs if i.shape == op.outputs[0].shape]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200403 op.type = Op.Identity
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200404 return op
405
406
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100407def rewrite_fully_connected_input(op, arch, nng):
408 if op.type == Op.FullyConnected:
409 n_in_elems = op.weights.shape[-2]
410 elms = op.ifm.elements()
411 batch_size = elms // n_in_elems
412 assert batch_size * n_in_elems == elms
413
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100414 op.ifm_shapes[0] = Shape4D([batch_size, 1, 1, n_in_elems])
Patrik Gustavssonda2b0032021-02-04 16:28:29 +0100415 if Shape4D(op.ifm.shape) != op.ifm_shapes[0]:
416 op.ifm.avoid_NHCWB16 = True
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100417 return op
418
419
Diqing Zhong94457b12020-12-09 15:22:40 +0100420def convert_batched_fc_shape(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200421 if op.type == Op.FullyConnected:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100422 # Check if the first dimension indicates batching
423 if op.ifm_shapes[0].batch > 1:
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200424 batching_split = {4: (2, 2), 8: (2, 4), 16: (4, 4)}
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100425 n = op.ifm_shapes[0].batch
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200426 h, w = batching_split.get(n, (1, n))
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100427 op.ifm_shapes[0] = Shape4D([1, h, w, op.ifm_shapes[0].depth])
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200428
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100429 op.ifm.avoid_NHCWB16 = True
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200430
431 # Reshape Weights to be 4D. IO becomes HWIO
432 weight_tensor = op.inputs[1]
433 weight_tensor.quant_values = np.expand_dims(np.expand_dims(weight_tensor.quant_values, axis=0), axis=0)
434 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
435
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100436 n = op.ofm_shapes[0].batch
437 h, w = batching_split.get(n, (1, n))
438 op.ofm_shapes[0] = Shape4D([1, h, w, op.ofm_shapes[0].depth])
439 op.ofm.avoid_NHCWB16 = True
Tim Hall79d07d22020-04-27 18:20:16 +0100440 return op
441
442
Patrik Gustavsson7bada402021-01-28 15:46:21 +0100443def unfuse_activation_function(op):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200444 if op.type == Op.ConcatTFLite and op.run_on_npu and op.activation is not None:
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100445 act_op = Operation(op.activation.op_type, op.name + op.activation.op_type.name)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200446 op.activation = None
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200447 out_tens = op.outputs[0]
448 intermediate_tens = out_tens.clone("_act_intermediate")
449 act_op.set_output_tensor(out_tens)
450 act_op.add_input_tensor(intermediate_tens)
451 op.set_output_tensor(intermediate_tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000452 act_op.set_ifm_ofm_shapes()
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200453
Louis Verhaard8912c532020-09-30 12:11:49 +0200454
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100455def rewrite_stridedslice_output(op, arch, nng):
456 if not op.run_on_npu or op.type != Op.StridedSlice:
457 return op
458
459 new_axis_mask = op.attrs["new_axis_mask"]
460 shrink_axis_mask = op.attrs["shrink_axis_mask"]
461
462 if shrink_axis_mask == 0 and new_axis_mask == 0:
463 return op
464
465 axis_4D = [0] * len(op.outputs)
466 for idx, out_tens in enumerate(op.outputs):
467 output_shape = list(out_tens.shape)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100468
Dwight Lidman73320a42020-11-05 10:34:41 +0100469 if shrink_axis_mask != 0:
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100470 n = 0
471 axis = 0
472 while shrink_axis_mask:
473 prev_mask = shrink_axis_mask
474 n += 1
475 shrink_axis_mask &= shrink_axis_mask - 1
476 axis = int(math.log2(prev_mask - shrink_axis_mask))
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100477 output_shape = output_shape[:axis] + [1] + output_shape[axis:]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100478
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100479 assert len(out_tens.shape) == (len(op.inputs[0].shape) - n)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100480 op.attrs["shrink_axis_mask"] = 0
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100481 if axis >= 0:
482 axis_4D[idx] = axis + (4 - len(output_shape))
483 else:
484 axis_4D[idx] = axis
485 op.ofm_shapes[idx] = Shape4D(output_shape)
486
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100487 elif new_axis_mask != 0:
488 n = 0
489 axis = 0
490 while new_axis_mask:
491 prev_mask = new_axis_mask
492 n += 1
493 new_axis_mask &= new_axis_mask - 1
494 axis = int(math.log2(prev_mask - new_axis_mask))
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100495 output_shape = output_shape[:axis] + output_shape[(axis + 1) :]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100496 new_axis_mask >>= 1
497
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100498 assert len(out_tens.shape) == (len(op.inputs[0].shape) + n)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100499 op.attrs["new_axis_mask"] = 0
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100500 if axis >= 0:
501 axis_4D[idx] = axis + (4 - len(output_shape))
502 else:
503 axis_4D[idx] = axis
504 op.ofm_shapes[idx] = Shape4D(output_shape)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100505
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100506 if op.ofm_shapes[idx] != Shape4D(out_tens.shape):
507 out_tens.avoid_NHCWB16 = True
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100508
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100509 op.attrs["split_axis_4D"] = axis_4D
510 return op
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100511
512
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100513def rewrite_unpack_output(op, arch, nng):
514 tens = op.outputs[0]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100515 if op.run_on_npu and op.type == Op.Unpack:
Tim Hall79d07d22020-04-27 18:20:16 +0100516 # Unpack is also referred to as Unstack
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100517 axis = int(op.attrs["axis"])
518 op.type = Op.UnpackReshaped
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100519 desired_output_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100520
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100521 if axis >= 0:
522 axis_4D = axis + (4 - len(desired_output_shape))
523 else:
524 axis_4D = axis
Tim Hall79d07d22020-04-27 18:20:16 +0100525
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100526 axis_4D_list = [0] * len(op.outputs)
Tim Hall79d07d22020-04-27 18:20:16 +0100527 for idx, out_tens in enumerate(op.outputs):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100528 op.ofm_shapes[idx] = Shape4D(desired_output_shape)
529 axis_4D_list[idx] = axis_4D
530 if op.ofm_shapes[idx] != Shape4D(out_tens.shape):
531 out_tens.avoid_NHCWB16 = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100532
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100533 op.attrs["split_axis_4D"] = axis_4D_list
534 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100535
536
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200537def add_padding_fields(op, arch, nng):
Jacob Bohlin90033f32020-08-28 15:45:44 +0200538 if op.run_on_npu:
539 if "padding" in op.attrs:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100540 input_shape = op.ifm_shapes[0]
541 output_shape = op.ofm_shapes[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200542 if op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op():
Jacob Bohlin90033f32020-08-28 15:45:44 +0200543 kernel_size = op.inputs[1].shape[:2]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200544 elif op.type.is_pool_op() or op.type.npu_block_type == NpuBlockType.ReduceSum:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200545 kernel_size = op.attrs["ksize"][1:3]
Jacob Bohlin90033f32020-08-28 15:45:44 +0200546 else:
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000547 raise UnsupportedFeatureError(f"Unknown operation that uses padding: {optype_to_builtintype(op.type)}")
Tim Hall79d07d22020-04-27 18:20:16 +0100548
Louis Verhaardaee5d752020-09-30 09:01:52 +0200549 if op.type == Op.Conv2DBackpropInputSwitchedBias:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100550 upscaling_factor = output_shape.height // input_shape.height
Jacob Bohlin90033f32020-08-28 15:45:44 +0200551 padding, skirt = calc_upscaled_padding_and_skirt(
552 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
553 )
554 else:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200555 padding, skirt = calc_padding_and_skirt(
Louis Verhaardebf4af62021-01-27 15:57:57 +0100556 op.attrs["padding"], op.kernel, input_shape, op.attrs.get("explicit_padding"),
Jacob Bohlin90033f32020-08-28 15:45:44 +0200557 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200558
Jacob Bohlin90033f32020-08-28 15:45:44 +0200559 op.attrs["explicit_padding"] = padding
560 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200561
Tim Hall79d07d22020-04-27 18:20:16 +0100562 return op
563
564
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200565def convert_depthwise_to_conv(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100566 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
567 # the ofm depth equals the depth multipler.
568 # If those conditions are true, then we can perform a simple
569 # switch of the operator type (and weight order)
570
Louis Verhaardaee5d752020-09-30 09:01:52 +0200571 if op.type == Op.DepthwiseConv2DBias and (op.attrs["depth_multiplier"] != 1):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100572 ifm_shape = op.ifm_shapes[0]
Tim Hall79d07d22020-04-27 18:20:16 +0100573 weight_tensor = op.inputs[1]
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100574 ofm_shape = op.ofm_shapes[0]
575 if (ifm_shape.depth == 1) and (ofm_shape.depth == op.attrs["depth_multiplier"]):
Tim Hall79d07d22020-04-27 18:20:16 +0100576 # Change op type to Conv2d
Louis Verhaardaee5d752020-09-30 09:01:52 +0200577 op.type = Op.Conv2DBias
Tim Hall79d07d22020-04-27 18:20:16 +0100578 del op.attrs["channel_multiplier"]
579 del op.attrs["depth_multiplier"]
580
581 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100582 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100583 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200584 raise UnsupportedFeatureError(
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000585 f"Unsupported 'DEPTHWISE_CONV_2D' with depth_multiplier = {op.attrs['depth_multiplier']},",
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100586 f" ifm channels = {ifm_shape.depth}, ofm channels = {ofm_shape.depth}",
Tim Hall79d07d22020-04-27 18:20:16 +0100587 )
Tim Halle6ccd872020-11-09 16:46:37 +0000588 DebugDatabase.add_optimised(op, op)
Tim Hall79d07d22020-04-27 18:20:16 +0100589 return op
590
591
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200592def reorder_depthwise_weights(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200593 if op.type.is_depthwise_conv2d_op():
Jacob Bohline843d332020-06-23 12:12:56 +0200594 weight_tensor = op.inputs[1]
595 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100596 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200597 weight_tensor.weight_transpose_depthwise = True
598
599 return op
600
601
Diqing Zhong016b8272020-12-16 16:46:06 +0100602def optimise_strided_conv(op, arch, nng):
603 stride_x, stride_y = op.get_kernel_stride()
604 ifm_tensor, _, weight_tensor, _ = op.get_ifm_ifm2_weights_ofm()
605
606 if (
607 op.type == Op.Conv2DBias
608 and op.op_index == 0
609 and stride_x == 2
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100610 and op.ifm_shapes[0].depth <= 4
611 and op.ifm_shapes[0].width % 2 == 0
Diqing Zhong016b8272020-12-16 16:46:06 +0100612 and weight_tensor is not None
613 and weight_tensor.shape[1] >= 2
614 ):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100615 ifm_shape = op.ifm_shapes[0]
Diqing Zhong016b8272020-12-16 16:46:06 +0100616 # IFM
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100617 op.ifm_shapes[0] = Shape4D([ifm_shape.batch, ifm_shape.height, ifm_shape.width // 2, ifm_shape.depth * 2])
618 op.ifm.avoid_NHCWB16 = True
Diqing Zhong016b8272020-12-16 16:46:06 +0100619
620 # Weights
621 weight_shape = weight_tensor.shape
622 if weight_shape[1] % 2 != 0:
623 weight_shape[1] = weight_shape[1] + 1
624 padded_array = np.zeros(weight_shape)
625 for i in range(weight_shape[0]):
626 padded_array[i] = np.vstack(
627 [
628 weight_tensor.quant_values[i],
629 np.full((1, weight_shape[2], weight_shape[3]), weight_tensor.quantization.zero_point),
630 ]
631 )
632 weight_tensor.quant_values = padded_array
633 weight_shape[1] //= 2
634 weight_shape[2] *= 2
635 weight_tensor.quant_values = np.reshape(weight_tensor.quant_values, weight_shape)
636 weight_tensor.set_all_shapes(weight_shape)
637 # If multiple copies of the weights are used, we could avoid
638 # them having the same address by changing the value_id
639 weight_tensor.value_id = uuid.uuid4()
640
641 # Strides
642 stride_x = 1
643 op.attrs.update({"stride_w": stride_x, "stride_h": stride_y, "strides": (1, stride_y, stride_x, 1)})
644
Diqing Zhong016b8272020-12-16 16:46:06 +0100645 return op
646
647
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200648def convert_conv_to_fc(op, arch, nng):
Michael McGeagh8d939c02020-07-29 13:11:43 +0100649 # Conv 1x1 can be equivalent to Fully Connected.
650 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
651 # caching/double buffering for the weights.
652 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200653 if op.type == Op.Conv2DBias:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000654 h = op.ifm_shapes[0].height
655 w = op.ifm_shapes[0].width
Michael McGeagh8d939c02020-07-29 13:11:43 +0100656 kh, kw, _, _ = op.inputs[1].shape
657 if h == 1 and w == 1 and kh == 1 and kw == 1:
658 # Overwrite this op as a Fully Connected Op
659 op.name += "_fc"
Louis Verhaardaee5d752020-09-30 09:01:52 +0200660 op.type = Op.FullyConnected
Michael McGeagh8d939c02020-07-29 13:11:43 +0100661 op.attrs = {
Michael McGeagh8d939c02020-07-29 13:11:43 +0100662 "weights_format": 0,
Michael McGeagh8d939c02020-07-29 13:11:43 +0100663 }
664 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
665 weight_tensor = op.inputs[1]
666 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
667 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100668
Tim Halle6ccd872020-11-09 16:46:37 +0000669 DebugDatabase.add_optimised(op, op)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100670 return op
671
672
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200673def fixup_relus_with_differing_ifm_ofm_scaling(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200674 if op.run_on_npu and op.type.is_relu_op():
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100675 ifm = op.inputs[0]
676 ofm = op.outputs[0]
677 # Relu with differing IFM and OFM scaling cannot be fused with another primary op
678 # and requires its own to be inserted
Tim Hall93582962020-09-09 21:58:15 +0100679 if not check_quantized_tens_scaling_equal(ifm, ofm):
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100680 # Override this op with its own primary op (avgpool)
681 relu_fused_op = create_avgpool_nop(op.name + "_avgpool")
682 # And fuse the original activation function to it
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100683 relu_fused_op.activation = create_activation_function(op.type)
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100684 # Tidy up and assign the ifm and ofm to the new op
685 ifm.consumer_list.remove(op)
Andreas Nevalainenf3d737e2020-09-25 14:12:43 +0200686
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100687 relu_fused_op.add_input_tensor(ifm)
688 relu_fused_op.set_output_tensor(ofm)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000689 relu_fused_op.set_ifm_ofm_shapes()
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100690 op = relu_fused_op
691 return op
692
693
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200694def fixup_elementwise_with_scalars(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200695 if op.type.is_binary_elementwise_op():
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200696 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200697 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
698 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
699 if diff > 0:
700 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
701 elif diff < 0:
702 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200703 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
704 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
705 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
706 ifm_tensor.storage_shape = ifm_tensor.shape
707 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
708 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
709 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
710 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200711 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100712
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200713
Tim Hall4e127762020-05-15 16:05:49 +0100714# Set input/output tensor equivalence to the same id for memory operations
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200715def set_tensor_equivalence(op, arch, nng):
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100716 if op.type in memory_only_ops:
Tim Hall4e127762020-05-15 16:05:49 +0100717 eid = op.outputs[0].equivalence_id
718 for inp in op.inputs:
719 inp.equivalence_id = eid
720 return op
721
722
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100723def set_ifm_ofm_op_shapes(op, arch, nng):
724 if op.run_on_npu and op.type.needs_shapes():
725 if op.ifm_shapes or op.ofm_shapes:
726 # Shapes already set
727 return op
728 op.set_ifm_ofm_shapes()
729 return op
730
731
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200732def convert_softmax(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200733 if op.type == Op.Softmax and op.run_on_npu:
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200734 softmax = SoftMax(op)
735 op = softmax.get_graph()
736 return op
737
738
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200739def convert_mul_max_to_abs_or_lrelu(op, arch, nng):
Diego Russoea6111a2020-04-14 18:41:58 +0100740 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100741
742 Input X For X = -1 or X > 0
743 | \ / This subgraph can be replaced with either
744 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
745 | /
746 Max
747 """
748
Louis Verhaardaee5d752020-09-30 09:01:52 +0200749 if op.type == Op.Maximum:
Tim Hall79d07d22020-04-27 18:20:16 +0100750 # finds the Mul input(s) to the Max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200751 muls = [i for i in op.inputs if i.ops[0].type == Op.Mul]
Tim Hall79d07d22020-04-27 18:20:16 +0100752 if len(muls) == 1:
753 mul = muls[0].ops[0]
754 elif len(muls) == 2:
755 # In the case both inputs are Muls, find the one with the same input as the Max
756 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
757 else:
758 # No Mul inputs
759 return op
760
761 # make sure the Mul doesn't have any other consumers
Louis Verhaardd7911c42020-08-25 13:36:41 +0200762 mul_ofm = mul.outputs[0]
763 if len(mul_ofm.consumers()) != 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100764 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200765 # make sure the Mul doesn't have a fused activation function
766 if mul.activation:
Tim Hall79d07d22020-04-27 18:20:16 +0100767 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200768 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100769 if ifm is None or ofm is None:
770 return op
771
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200772 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
773 return op
Tim Hall93582962020-09-09 21:58:15 +0100774 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 +0200775 # rewrite to LeakyRelu currently only makes sense if the quantization is identical
776 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100777
778 # finds the branched input that goes to both the Max and the Mul
779 shared = set(op.inputs) & set(mul.inputs)
780 if len(shared) == 1:
781 shared_in = shared.pop()
782 # find the constant scalar input to the Mul
783 const_tens = (set(mul.inputs) - {shared_in}).pop()
784 # check that it is a scalar
785 if const_tens.shape != []:
786 return op
787 const = const_tens.ops[0]
788 # check that it is a constant
Louis Verhaardaee5d752020-09-30 09:01:52 +0200789 if const.type != Op.Const:
Tim Hall79d07d22020-04-27 18:20:16 +0100790 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200791 # Remove the Mul from the shared input's consumers
792 shared_in.consumer_list.remove(mul)
Tim Hall79d07d22020-04-27 18:20:16 +0100793 else:
794 return op
795
796 val = const.outputs[0].values
797 if val >= 0:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200798 new_op = Op.LeakyRelu
Tim Hall79d07d22020-04-27 18:20:16 +0100799 op.attrs["alpha"] = val
Louis Verhaardd7911c42020-08-25 13:36:41 +0200800 # to produce bit exact results, the alpha is not enough;
801 # save additional scaling info in attr "alpha_scale", to be used as input
802 # to the LUT construction
803 alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point
804 mul_ifm_scale = np.double(ifm.quantization.scale_f32)
805 mul_ifm2_scale = np.double(const_tens.quantization.scale_f32)
806 mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32)
807 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale)
808 op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift)
Tim Hall79d07d22020-04-27 18:20:16 +0100809 elif val == -1:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200810 new_op = Op.Abs
Tim Hall79d07d22020-04-27 18:20:16 +0100811 else:
812 return op
813
Louis Verhaardaee5d752020-09-30 09:01:52 +0200814 op.type = new_op
815 op.name = op.name.replace("Maximum", new_op.name)
816 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100817 op.inputs = [shared_in]
Patrik Gustavssonc509d332020-12-22 13:53:52 +0100818 op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000819
820 # Record optimisation in debug database
821 DebugDatabase.add_optimised(op, op)
822
Tim Hall79d07d22020-04-27 18:20:16 +0100823 return op
824
825
Diqing Zhong189f7482021-01-26 12:12:51 +0100826def convert_hardswish_to_lut(op, arch, nng):
827 if op.type == Op.HardSwish:
828 ifm, ofm = op.get_ifm_ofm()
829 # Generate the LUT
830 ifm_scale = np.double(ifm.quantization.scale_f32)
831 ofm_scale = np.double(ofm.quantization.scale_f32)
832 zp_in = ifm.quantization.zero_point
833 zp_out = ofm.quantization.zero_point
834 ifm_scale_hires = (1 / 128) * ifm_scale
835 relu_multiplier = np.double(3 / 32768)
836 out_scale, out_shift = scaling.quantise_scale(ifm_scale_hires / ofm_scale)
837 relu_scale, relu_shift = scaling.quantise_scale(ifm_scale_hires / relu_multiplier)
838 # Use 16bit scale
839 out_scale_16 = fp_math.downscale_multiplier_int32_to_int16(out_scale)
840 relu_scale_16 = fp_math.downscale_multiplier_int32_to_int16(relu_scale)
841
842 values = []
843 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
844 quantized_min = min(ix)
845 quantized_max = max(ix)
846 for x in ix:
847 input_value = x - zp_in
848 input_value_hires = input_value * 128
849 # Compute the input value on essentially the output scale, not shifted yet
850 input_value_preshift = fp_math.saturating_rounding_mul16(input_value_hires, out_scale_16)
851 # Compute the "relu-ish multiplier". This matches the code in TensorFlow Lite Micro kernel
852 relu_value = np.int16(input_value_hires)
853 if relu_shift < 31:
854 relu_value = fp_math.shift_left16(relu_value, 30 - relu_shift)
855
856 relu_value = fp_math.saturating_rounding_mul16(relu_value, relu_scale_16)
857
858 if relu_shift < 31:
859 relu_value = fp_math.shift_left16(relu_value, 1)
860
861 if relu_shift > 31:
862 relu_value = fp_math.rounding_divide_by_pot(relu_value, relu_shift - 31)
863
864 # Rescaled the value into a 16bit fixedpoint relu_value in [-1, 1]
865 # Now convert that to a 16bit fixedpoint value in [0, 1]
866 relu_value = (relu_value + (1 << 15)) >> 1
867 lut_result = fp_math.saturating_mul16(relu_value, input_value_preshift)
868 shift = 31 - out_shift
869 shift = -shift if shift < 0 else 0
870 # Finally apply the output shift
871 lut_result = fp_math.rounding_divide_by_pot(lut_result, shift) + zp_out
872 lut_result = min(quantized_max, max(quantized_min, lut_result))
873 values.append(lut_result)
874 return convert_to_lut(op, values, "hardswish")
875 return op
876
877
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200878def convert_lrelu_to_mul_max(op, arch):
879 # Converts LeakyRelu to Max(alpha * IFM, identity * IFM)
880 # (the opposite of convert_mul_max_to_abs_or_lrelu)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200881 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100882 if ifm is None or ofm is None:
883 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200884
885 # Add multiplication with alpha
Louis Verhaardaee5d752020-09-30 09:01:52 +0200886 mul_alpha = Operation(Op.Mul, op.name + "_mul_alpha")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200887 mul_alpha.add_input_tensor(ifm)
888 # Create const tensor containing alpha as scalar
889 alpha = op.attrs["alpha"]
890 quantization = ifm.quantization.clone()
891 quantization.min = 0
892 quantization.max = alpha * (quantization.quant_max - quantization.quant_min)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200893 quantization.zero_point = 0
Louis Verhaardece4e652021-01-07 13:35:47 +0100894 if np.isinf(1 / np.float32(alpha)):
895 # Handling of alpha near zero
896 quantization.scale_f32 = 1
897 scalar = 0
898 else:
899 quantization.scale_f32 = alpha
900 scalar = 1
901 alpha_tens = create_const_tensor(
902 op.name + "_alpha_scalar", [], ifm.dtype, [scalar], np.int8, quantization=quantization
903 )
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200904 mul_alpha.add_input_tensor(alpha_tens)
905 fm_alpha = ofm.clone(op.name + "_alpha")
906 mul_alpha.set_output_tensor(fm_alpha)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000907 mul_alpha.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000908 DebugDatabase.add_optimised(op, mul_alpha)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200909
Tim Hall93582962020-09-09 21:58:15 +0100910 if check_quantized_tens_scaling_equal(ifm, ofm):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200911 # No identity multiplication is needed
912 fm_id = ifm
913 else:
914 # Add multiplication with identity
Louis Verhaardaee5d752020-09-30 09:01:52 +0200915 mul_identity = Operation(Op.Mul, op.name + "_mul_identity")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200916 mul_identity.add_input_tensor(ifm)
917 # Create const tensor containing identity as scalar
918 quantization = ifm.quantization.clone()
919 quantization.min = 0
920 quantization.max = quantization.quant_max - quantization.quant_min
921 quantization.scale_f32 = 1
922 quantization.zero_point = 0
923 identity_tens = create_const_tensor(
924 op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization
925 )
926 mul_identity.add_input_tensor(identity_tens)
Louis Verhaardece4e652021-01-07 13:35:47 +0100927 # Make sure that fm_id is allocated to a different address than fm_alpha
928 fm_id = ofm.clone(op.name + "_id", set_unique=True)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200929 mul_identity.set_output_tensor(fm_id)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000930 mul_identity.set_ifm_ofm_shapes()
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100931 DebugDatabase.add_optimised(op, mul_identity)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200932
933 # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs
Louis Verhaardaee5d752020-09-30 09:01:52 +0200934 op.type = Op.Maximum
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200935 op.name = op.name.replace("LeakyRelu", "Maximum")
936 op.inputs = []
937 ifm.consumer_list.remove(op)
938 op.add_input_tensor(fm_alpha)
939 op.add_input_tensor(fm_id)
Patrik Gustavssonc509d332020-12-22 13:53:52 +0100940 op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000941
942 DebugDatabase.add_optimised(op, op)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200943 return op
944
945
Louis Verhaard2e186c72020-10-09 10:47:04 +0200946def convert_to_lut(op, lut_values, lut_name):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200947 # Rewrite the operation by Add with scalar 0 + LUT activation
948 ifm = op.inputs[0]
Tim Hall93582962020-09-09 21:58:15 +0100949 if ifm is None:
950 return op
Louis Verhaard58520b92020-08-24 16:45:38 +0200951 assert ifm.dtype.size_in_bytes() == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +0200952 op.type = Op.Add
Louis Verhaard2e186c72020-10-09 10:47:04 +0200953 op.name = op.name + "_lut_" + lut_name
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200954 # Mark as no-op to enable potential fusing optimizations
955 op.attrs["is_nop"] = True
956 # Create an input tensor containing scalar zero
957 quantization = QuantizationParameters(0.0, 255.0)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200958 quantization.scale_f32 = ifm.quantization.scale_f32
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200959 quantization.zero_point = 0
Louis Verhaard2e186c72020-10-09 10:47:04 +0200960 tens = create_const_tensor(op.inputs[0].name + "_scalar0", [], ifm.dtype, [0], np.uint8, quantization=quantization)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200961 op.add_input_tensor(tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000962 op.ifm_shapes.append(Shape4D(tens.shape))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100963
Louis Verhaardf03bad32020-09-25 08:30:44 +0200964 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
965 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
966 # should be the same as the IFM
Louis Verhaardaee5d752020-09-30 09:01:52 +0200967 op.forced_output_quantization = ifm.quantization
Louis Verhaard2e186c72020-10-09 10:47:04 +0200968 lut_tensor = lut.create_lut_tensor(op.name + "_values", lut_values, DataType.int8)
Louis Verhaardf03bad32020-09-25 08:30:44 +0200969 op.set_activation_lut(lut_tensor)
Patrik Gustavssonc509d332020-12-22 13:53:52 +0100970 op.set_ifm_ofm_shapes()
Louis Verhaardf03bad32020-09-25 08:30:44 +0200971 return op
972
973
Louis Verhaard2e186c72020-10-09 10:47:04 +0200974def convert_to_lut8(op, fn, fn_name):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200975 # Converts op to a no-op + int8/uint8 LUT which is generated with the given function.
976 # fn is a function(real) -> real
Louis Verhaardaee5d752020-09-30 09:01:52 +0200977 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardf03bad32020-09-25 08:30:44 +0200978 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
979 return op
980 # Generate the LUT
981 ifm_scale = np.double(ifm.quantization.scale_f32)
982 ofm_scale = np.double(ofm.quantization.scale_f32)
983 zp_in = ifm.quantization.zero_point
984 zp_out = ofm.quantization.zero_point
985 values = []
986 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
987 quantized_min = min(ix)
988 quantized_max = max(ix)
989 for x in ix:
990 x_real = ifm_scale * (x - zp_in)
991 y_real = fn(x_real)
992 lut_result = round_away_zero(zp_out + y_real / ofm_scale)
993 lut_result = min(quantized_max, max(quantized_min, lut_result))
994 values.append(lut_result)
Louis Verhaard2e186c72020-10-09 10:47:04 +0200995 return convert_to_lut(op, values, fn_name)
Louis Verhaardf03bad32020-09-25 08:30:44 +0200996
997
998def convert_lrelu_to_lut(op, arch):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200999 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001000 # Generate the LUT
Louis Verhaardd7911c42020-08-25 13:36:41 +02001001 alpha = op.attrs["alpha"]
1002 ifm_scale = np.double(ifm.quantization.scale_f32)
1003 ofm_scale = np.double(ofm.quantization.scale_f32)
1004 zp_in = ifm.quantization.zero_point
1005 zp_out = ofm.quantization.zero_point
1006 identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale)
1007 alpha_scalar = 1
1008 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale)
1009 if "alpha_scaling" in op.attrs:
1010 # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu
1011 alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"]
1012 values = []
Louis Verhaard58520b92020-08-24 16:45:38 +02001013 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
Louis Verhaardd7911c42020-08-25 13:36:41 +02001014 quantized_min = min(ix)
1015 quantized_max = max(ix)
1016 for x in ix:
1017 if x < zp_in:
1018 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(
1019 alpha_scalar * (x - zp_in), alpha_scale, alpha_shift
1020 )
1021 else:
1022 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift)
1023 lut_result = min(quantized_max, max(quantized_min, lut_result))
1024 values.append(lut_result)
Louis Verhaard2e186c72020-10-09 10:47:04 +02001025 return convert_to_lut(op, values, "lrelu")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001026
1027
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001028def convert_lrelu(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001029 # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max
Louis Verhaardaee5d752020-09-30 09:01:52 +02001030 if op.type != Op.LeakyRelu:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001031 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001032 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +01001033 if ifm is None or ofm is None:
1034 return op
Louis Verhaardd7911c42020-08-25 13:36:41 +02001035 if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype:
1036 # use LUT for int8/uint8
1037 return convert_lrelu_to_lut(op, arch)
Tim Hall93582962020-09-09 21:58:15 +01001038 if check_quantized_tens_scaling_equal(ifm, ofm) and ifm.dtype == ofm.dtype == DataType.int16:
Louis Verhaardd7911c42020-08-25 13:36:41 +02001039 # use LeakyRelu unmodified for int16 with equal input/output scaling
1040 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001041 return convert_lrelu_to_mul_max(op, arch)
1042
1043
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001044def convert_tanh_sigmoid_to_lut(op, arch, nng):
Louis Verhaardf03bad32020-09-25 08:30:44 +02001045 # Converts int8/uint8 Sigmoid and Tanh to a LUT based solution
Louis Verhaardaee5d752020-09-30 09:01:52 +02001046 if op.type == Op.Sigmoid:
Louis Verhaard2e186c72020-10-09 10:47:04 +02001047 return convert_to_lut8(op, clamp_sigmoid, "sigmoid")
Louis Verhaardaee5d752020-09-30 09:01:52 +02001048 elif op.type == Op.Tanh:
Louis Verhaard2e186c72020-10-09 10:47:04 +02001049 return convert_to_lut8(op, math.tanh, "tanh")
Louis Verhaardf03bad32020-09-25 08:30:44 +02001050 return op
1051
1052
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001053def remove_reshapes(op, arch):
1054 if op.run_on_npu and op.type == Op.Reshape:
1055 ofm = op.ofm
1056 ifm = op.ifm
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001057
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001058 # Check if quantization is the same in the input and output for the reshape ops
1059 if not check_quantized_tens_scaling_equal(ifm, ofm):
1060 # TODO Both tensors are needed, since quantisation properties currently are linked to Tensors.
1061 # In order to remove this reshape either quantization properties need to be moved to Operator,
1062 # or the reshape need to be replace with a NOP.
1063 return
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001064
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001065 # Check if Reshape ifm/ofm are network ifm/ofm
Patrik Gustavsson138d47f2021-02-08 10:13:48 +01001066 ifm_is_sg_ifm = ifm.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const)
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001067 ifm_is_sg_ofm = any(ifm_cons is None for ifm_cons in ifm.consumer_list)
1068 ofm_is_sg_ofm = any(ofm_cons is None for ofm_cons in ofm.consumer_list)
Patrik Gustavsson138d47f2021-02-08 10:13:48 +01001069 # This case should be handled prior to this function
1070 assert not ((ifm_is_sg_ifm or ifm_is_sg_ofm) and ofm_is_sg_ofm)
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001071
1072 if ofm_is_sg_ofm:
1073 # Bypassed by replacing ifm with ofm
1074 ofm.ops = []
1075 for prev_op in ifm.ops:
1076 prev_op.outputs = [ofm]
1077 ofm.ops.append(prev_op)
1078
1079 # All ifm consumers need to use ofm as input
1080 for ifm_cons in ifm.consumer_list:
1081 for ifm_idx, cons_ifm in enumerate(ifm_cons.inputs):
1082 if cons_ifm == ifm:
1083 ifm_cons.set_input_tensor(ofm, ifm_idx)
1084 if op.ifm_shapes[0] != op.ofm_shapes[0]:
1085 ofm.avoid_NHCWB16 = True
1086 else:
1087 # Bypassed Reshape by replacing ofm with ifm
1088 for cons in ofm.consumer_list:
1089 for ifm_idx, cons_ifm in enumerate(cons.inputs):
1090 if cons_ifm == ofm:
1091 cons.set_input_tensor(ifm, ifm_idx)
1092 if op.ifm_shapes[0] != op.ofm_shapes[0]:
1093 ifm.avoid_NHCWB16 = True
1094
1095
1096def check_reshapes(op, arch):
1097 if op.run_on_npu and op.type == Op.Reshape:
1098 ofm = op.ofm
1099
1100 if check_quantized_tens_scaling_equal(op.ifm, ofm):
1101 # Reshape should have been removed
1102 raise VelaError(f"Reshape op {op} expected to have been removed, still remains")
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001103
1104
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001105def fuse_activation_function_with_prev(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001106 # if op is a no-op: attempts to move the activation function to the preceding op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001107 if not op.attrs.get("is_nop", False) or op.activation is None:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001108 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001109 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +01001110 if ifm is None or ofm is None:
1111 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001112 # finds the input(s) to the operation
1113 prev_op = ifm.ops[0]
1114 # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed
1115 fuse = (
1116 prev_op.run_on_npu
Louis Verhaardaee5d752020-09-30 09:01:52 +02001117 and prev_op.type.npu_block_type != NpuBlockType.Default
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001118 and len(ifm.ops) == 1
1119 and len(prev_op.outputs[0].consumers()) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +02001120 and prev_op.activation is None
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001121 )
1122 if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0:
1123 # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC),
1124 # LUT currently only works correctly for elementwise ops
1125 fuse = False
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001126 if not fuse:
1127 return op
1128 # Move the fused activation function + corresponding info to prev_op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001129 prev_op.activation = op.activation
1130 prev_op.forced_output_quantization = op.forced_output_quantization
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001131 if op.activation_lut is not None:
1132 prev_op.set_activation_lut(op.activation_lut)
1133 # Bypass op
Louis Verhaard98a34992020-09-01 10:39:04 +02001134 prev_op.set_output_tensor(ofm)
Tim Halle6ccd872020-11-09 16:46:37 +00001135 DebugDatabase.add_optimised(op, prev_op)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001136 return op
1137
1138
Louis Verhaardae2d5532020-12-11 17:19:54 +01001139def optimise_pad(op, arch, nng):
1140 """
1141 Converts tens1 -> PAD -> tens2 -> CONV to tens1 -> CONV
1142 if both operations can be run on the NPU.
1143 """
1144 if (
1145 (op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op())
1146 and op.run_on_npu
1147 and op.attrs["padding"] == Padding.VALID
1148 ):
1149 pad_op = op.ifm.ops[0]
1150 if pad_op.type != Op.Pad or not pad_op.run_on_npu:
1151 return op
1152 # Bypass the PAD operator
1153 op.set_input_tensor(pad_op.ifm, 0)
1154 # Adjust the padding attributes of the convolution operator
1155 op.attrs["padding"] = Padding.EXPLICIT
1156 padding = pad_op.inputs[1].values # 4x2 tensor, first dimension is N, H, W, C
1157 top, left, bottom, right = (padding[1][0], padding[2][0], padding[1][1], padding[2][1])
1158 op.attrs["explicit_padding"] = (top, left, bottom, right)
1159 op.set_ifm_ofm_shapes()
1160 return op
1161
1162
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001163def add_attrs_to_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001164 if op.type == Op.ResizeBilinear and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +02001165 input_tensor = op.inputs[0]
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001166 input_shape = op.ifm_shapes[0]
1167 upscaled_height = input_shape.height * 2
1168 upscaled_width = input_shape.width * 2
1169 out_shape = op.ofm_shapes[0]
1170 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 +02001171 # this means the output is supposed to be a x2 upscale,
1172 # so we need to do SAME padding
Michael McGeagh16895482020-12-14 15:51:20 +00001173 op.attrs["padding"] = Padding.SAME
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001174 elif (
1175 op.attrs["align_corners"]
1176 and out_shape.height == (upscaled_height - 1)
1177 and out_shape.width == (upscaled_width - 1)
1178 ):
Dwight Lidman42fed942020-05-29 09:37:03 +02001179 # here we can just run the avg pool without padding and
1180 # produce a (M * 2 - 1, N * 2 - 1) sized output
Michael McGeagh16895482020-12-14 15:51:20 +00001181 op.attrs["padding"] = Padding.VALID
Dwight Lidman42fed942020-05-29 09:37:03 +02001182 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +02001183 return op
Dwight Lidman42fed942020-05-29 09:37:03 +02001184 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +01001185 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +02001186 return op
1187
1188
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001189def fixup_bias_tensors(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001190 if op.type.needs_bias() and op.bias is None:
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001191 # Op has no bias, add bias tensor filled with zeros
1192 nr_biases = op.inputs[1].shape[-1]
1193 bias_values = [0] * nr_biases
1194 bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values)
1195 bias_tensor.quant_values = bias_tensor.values
1196 op.set_input_tensor(bias_tensor, -1)
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +02001197
1198 return op
1199
1200
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001201def supported_operator_check(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +01001202 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
1203 return op
1204
1205
Tim Halle6ccd872020-11-09 16:46:37 +00001206def _record_optimised(op, arch):
1207 if op.type != Op.Const:
1208 DebugDatabase.add_optimised(op, op)
1209
1210
Tim Hall79d07d22020-04-27 18:20:16 +01001211def optimise_graph_a(nng, arch, verbose_graph=False):
1212 if verbose_graph:
1213 nng.print_graph()
1214
Patrik Gustavsson2349d422020-12-01 16:02:29 +01001215 pre_process_list = [
1216 supported_operator_check,
1217 set_ifm_ofm_op_shapes,
1218 # TODO: memory-only Op removal
1219 ]
1220
1221 for idx, sg in enumerate(nng.subgraphs):
1222 # rewrite graph pass
1223 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1224 nng, sg, arch, [], pre_process_list, rewrite_unsupported=False,
1225 )
1226
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001227 # Handle Concat Ops
1228 for idx, sg in enumerate(nng.subgraphs):
1229 # rewrite graph pass
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +01001230 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [rewrite_concat_ops])
1231 sg.refresh_after_modification()
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001232
1233 # Handle Split Ops
1234 for idx, sg in enumerate(nng.subgraphs):
1235 # rewrite graph pass
1236 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1237 nng,
1238 sg,
1239 arch,
1240 [],
1241 [rewrite_unpack_output, rewrite_stridedslice_output, convert_nop_split_to_identity],
1242 rewrite_unsupported=False,
1243 )
1244
1245 for idx, sg in enumerate(nng.subgraphs):
1246 # rewrite graph pass
1247 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1248 nng, sg, arch, [rewrite_split_ops], [], rewrite_unsupported=False,
1249 )
1250
Patrik Gustavsson138d47f2021-02-08 10:13:48 +01001251 # Handle sg input output
1252 for idx, sg in enumerate(nng.subgraphs):
1253 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1254 nng, sg, arch, [], [fix_sg_input_output], rewrite_unsupported=False,
1255 )
1256
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001257 # Removal of reshapes
1258 for sg in nng.subgraphs:
1259 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [remove_reshapes])
1260 sg.refresh_after_modification()
1261
Tim Hall79d07d22020-04-27 18:20:16 +01001262 op_rewrite_list = [
Tim Hall4e127762020-05-15 16:05:49 +01001263 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +01001264 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +01001265 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +02001266 convert_softmax,
Diqing Zhong016b8272020-12-16 16:46:06 +01001267 optimise_strided_conv,
Diqing Zhong189f7482021-01-26 12:12:51 +01001268 convert_hardswish_to_lut,
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +01001269 rewrite_fully_connected_input,
Diqing Zhong94457b12020-12-09 15:22:40 +01001270 convert_batched_fc_shape,
Tim Hall79d07d22020-04-27 18:20:16 +01001271 fixup_conv2d_backprop,
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +01001272 fixup_relus_with_differing_ifm_ofm_scaling,
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001273 fixup_elementwise_with_scalars, # TODO Move to early stage?
Jacob Bohline843d332020-06-23 12:12:56 +02001274 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +02001275 fixup_resizebilinear,
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001276 fixup_bias_tensors,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001277 convert_mul_max_to_abs_or_lrelu,
1278 convert_lrelu,
Louis Verhaardf03bad32020-09-25 08:30:44 +02001279 convert_tanh_sigmoid_to_lut,
Tim Hall79d07d22020-04-27 18:20:16 +01001280 ]
1281
1282 for idx, sg in enumerate(nng.subgraphs):
1283 # rewrite graph pass
1284 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Dwight Lidman73320a42020-11-05 10:34:41 +01001285 nng, sg, arch, [], op_rewrite_list, rewrite_unsupported=False,
Tim Hall79d07d22020-04-27 18:20:16 +01001286 )
1287
1288 for idx, sg in enumerate(nng.subgraphs):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001289 # remove passthrough tensors and attempt further optimizations
1290 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Louis Verhaardae2d5532020-12-11 17:19:54 +01001291 nng,
1292 sg,
1293 arch,
1294 [remove_passthrough_tensor],
1295 [fuse_activation_function_with_prev, optimise_pad, add_padding_fields],
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001296 )
Tim Hall79d07d22020-04-27 18:20:16 +01001297
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001298 # Post-optimisation operator debug tracing, and checking that no undesired reshapes are left in the graph
Tim Halle6ccd872020-11-09 16:46:37 +00001299 for sg in nng.subgraphs:
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001300 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [check_reshapes, _record_optimised])
Tim Hall79d07d22020-04-27 18:20:16 +01001301
1302 if verbose_graph:
1303 nng.print_graph()
1304 return nng