blob: 50368b86b4436e4d69ac93cfd7417f9d903d774e [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
Tim Hall79d07d22020-04-27 18:20:16 +0100167
Patrik Gustavssone3b1b912021-02-09 15:38:46 +0100168 new_op.read_offsets[0] = Shape4D.from_list(offset_start, 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100169 new_op.run_on_npu = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100170 new_op.set_output_tensor(tens)
Patrik Gustavsson224e99b2021-01-14 10:55:43 +0100171 new_op.ifm_shapes.append(Shape4D(inp.shape))
Tim Hall73e843f2021-02-04 22:47:46 +0000172 new_op.ofm_shapes.append(split_op.ofm_shapes[ofm_shape_idx])
Tim Halle6ccd872020-11-09 16:46:37 +0000173 DebugDatabase.add_optimised(split_op, new_op)
Tim Hall79d07d22020-04-27 18:20:16 +0100174
175 return tens
176
177
Patrik Gustavssone3b1b912021-02-09 15:38:46 +0100178def remove_SplitSliceRead(op, arch):
179
180 if op.type == Op.SplitSliceRead:
181 # Check if it is possible to put the SplitSliceRead on the tensor consumer, or if an avgpool need to be inserted
182 if (
183 len(op.ofm.consumer_list) == 1
184 and op.ofm.consumer_list[0] is not None
185 and op.ofm.consumer_list[0].run_on_npu
186 and op.ofm.consumer_list[0].type != Op.Reshape
187 and op.ofm_shapes[0] == Shape4D.from_list(op.ofm.shape)
188 ):
189 # SplitSliceRead can be performed by tensor consumer
190 cons_op = op.ofm.consumer_list[0]
191 if cons_op.ifm == op.ofm:
192 cons_op.read_offsets[0] = op.read_offsets[0]
193 cons_op.set_input_tensor(op.ifm, cons_op.type.info.indices.ifms[0])
194 cons_op.ifm_shapes[0] = op.ifm_shapes[0]
195 elif cons_op.type.is_binary_elementwise_op() and cons_op.ifm2 == op.ofm:
196 cons_op.read_offsets[1] = op.read_offsets[0]
197 cons_op.set_input_tensor(op.ifm, cons_op.type.info.indices.ifms[1])
198 cons_op.ifm_shapes[1] = op.ifm_shapes[0]
199
200 op.ofm.consumer_list.remove(cons_op)
201 op.ofm.ops = []
202 op.ifm.consumer_list.remove(op)
203 else:
204 avgpool_op = create_avgpool_nop(op.name + "_avgpool")
205 avgpool_op.add_input_tensor(op.ifm)
206 avgpool_op.outputs = [op.ofm]
207 op.ofm.ops.remove(op)
208 op.ofm.ops.append(avgpool_op)
209 avgpool_op.ifm_shapes.append(op.ifm_shapes[0])
210 avgpool_op.ofm_shapes.append(op.ofm_shapes[0])
211 avgpool_op.read_offsets[0] = op.read_offsets[0]
212
213 op.ifm.consumer_list.remove(op)
214 DebugDatabase.add_optimised(op, avgpool_op)
215
216
Patrik Gustavsson138d47f2021-02-08 10:13:48 +0100217def insert_copy_op_after_tens(tens):
218 tens_cons_list_copy = tens.consumer_list.copy()
219
220 # Create a avg_pool nop op with ifm as input
221 copy_tens = tens.clone()
222 copy_op = create_avgpool_nop(tens.name + "_avgpool")
223 copy_op.add_input_tensor(tens)
224 copy_op.set_output_tensor(copy_tens)
225 copy_op.set_ifm_ofm_shapes()
226 copy_op.run_on_npu = True
227
228 # Set copy_ifm consumers
229 for tens_cons in tens_cons_list_copy:
230 if tens_cons is not None:
231 for ifm_idx, cons_inp in enumerate(tens_cons.inputs):
232 if cons_inp == tens:
233 tens_cons.set_input_tensor(copy_tens, ifm_idx)
234
235 DebugDatabase.add_optimised(tens.ops[0], copy_op)
236
237
238def fix_sg_input_output(op, arch, nng):
239 if not op.run_on_npu or op.type != Op.Reshape:
240 return op
241
Patrik Gustavssone3b1b912021-02-09 15:38:46 +0100242 # For the Reshape operators we want to remove, tensors are removed.
Patrik Gustavsson138d47f2021-02-08 10:13:48 +0100243 # But in order to to do this, they cannot be outputs of the sg,
244 # this need to be fixed prior to the removal.
245 # Solution is to add a avgpool NOP, to maintain the original tensor.
246
247 # Check if operator ifm/ofm are sg ifm/ofm
248 ifm_is_sg_ifm = op.ifm.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const)
249 ifm_is_sg_ofm = any(ifm_cons is None for ifm_cons in op.ifm.consumer_list)
250 ofm_is_sg_ofm = any(ofm_cons is None for ofm_cons in op.ofm.consumer_list)
251
252 if op.type == Op.Reshape and (ifm_is_sg_ofm or ifm_is_sg_ifm) and ofm_is_sg_ofm:
253 # Both ifm and ofm are sg outputs, only ifm need a copy, in order to remove the Reshape
254 insert_copy_op_after_tens(op.ifm)
255
256 return op
257
258
Tim Hall79d07d22020-04-27 18:20:16 +0100259def needed_total_padding(input_size, stride, filter_size):
260 out_size = (input_size + stride - 1) // stride
261 needed_input = (out_size - 1) * stride + filter_size
262 total_padding = max(0, needed_input - input_size)
263 return total_padding
264
265
Louis Verhaardebf4af62021-01-27 15:57:57 +0100266def calc_explicit_padding(input_size, stride, filter_size, pad_before, pad_after) -> Tuple[int, int]:
267 """
268 Based on explicit padding provided in a PAD operation, returns the corresponding hardware padding
269 that provides equivalent results.
270 """
271 total_padding = needed_total_padding(input_size, stride, filter_size)
272 # The top/left padding can be taken as is from the PAD
273 output_pad_before = pad_before
274 # The bottom/right padding might need downward adjustment depending on stride/input size
275 output_pad_after = pad_after
276 while output_pad_after > 0 and output_pad_after % stride != (total_padding - pad_before) % stride:
277 output_pad_after -= 1
278 return output_pad_before, output_pad_after
279
280
281def calc_padding_and_skirt(padding_type, kernel, input_shape, explicit_padding):
282 k_w, k_h = kernel.dilated_wh()
283 s_x, s_y = kernel.stride
284 ypad = needed_total_padding(int(input_shape.height), int(s_y), int(k_h))
285 xpad = needed_total_padding(int(input_shape.width), int(s_x), int(k_w))
Michael McGeagh16895482020-12-14 15:51:20 +0000286 if padding_type == Padding.SAME:
Tim Hall79d07d22020-04-27 18:20:16 +0100287 left_pad = (xpad + 0) // 2
288 right_pad = (xpad + 1) // 2
289 top_pad = (ypad + 0) // 2
290 bottom_pad = (ypad + 1) // 2
Michael McGeagh16895482020-12-14 15:51:20 +0000291 elif padding_type == Padding.VALID:
Tim Hall79d07d22020-04-27 18:20:16 +0100292 left_pad = 0
293 right_pad = 0
294 top_pad = 0
295 bottom_pad = 0
Louis Verhaardae2d5532020-12-11 17:19:54 +0100296 elif padding_type == Padding.EXPLICIT:
297 # Padding is specified in a PAD operator which has been bypassed.
Louis Verhaardebf4af62021-01-27 15:57:57 +0100298 top, left, bottom, right = explicit_padding
299 top_pad, bottom_pad = calc_explicit_padding(int(input_shape.height), int(s_y), int(k_h), int(top), int(bottom))
300 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 +0100301 else:
Michael McGeagh16895482020-12-14 15:51:20 +0000302 raise UnsupportedFeatureError(f"Unknown padding")
Tim Hall79d07d22020-04-27 18:20:16 +0100303 padding = (top_pad, left_pad, bottom_pad, right_pad)
304 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
305 return padding, skirt
306
Tim Hallc30f4952020-06-15 20:47:35 +0100307
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100308def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_shape, upscaling_factor):
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200309 kernel_height, kernel_width = kernel_size[0], kernel_size[1]
Michael McGeagh16895482020-12-14 15:51:20 +0000310 if padding_type == Padding.SAME:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100311 ypad = needed_total_padding(int(input_shape.height) * upscaling_factor, int(stride[1]), int(kernel_height))
312 xpad = needed_total_padding(int(input_shape.width) * upscaling_factor, int(stride[2]), int(kernel_width))
Jacob Bohlind47cc272020-08-24 11:42:14 +0200313 right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0)
314 bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200315 left_pad = max(kernel_width - 1 - right_pad, 0)
316 top_pad = max(kernel_height - 1 - bottom_pad, 0)
Michael McGeagh16895482020-12-14 15:51:20 +0000317 elif padding_type == Padding.VALID:
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200318 right_pad = max(kernel_width - 2, 0)
319 bottom_pad = max(kernel_height - 2, 0)
320 left_pad = kernel_width - 1
321 top_pad = kernel_height - 1
Jacob Bohlincf7da102020-05-20 09:03:40 +0200322 else:
Michael McGeagh16895482020-12-14 15:51:20 +0000323 raise UnsupportedFeatureError(f"Unknown padding")
Jacob Bohlincf7da102020-05-20 09:03:40 +0200324 padding = (top_pad, left_pad, bottom_pad, right_pad)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200325 skirt = padding
Jacob Bohlincf7da102020-05-20 09:03:40 +0200326 return padding, skirt
327
Tim Hall79d07d22020-04-27 18:20:16 +0100328
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200329def fixup_conv2d_backprop(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200330 if op.type == Op.Conv2DBackpropInput:
Tim Hall79d07d22020-04-27 18:20:16 +0100331 # flip the inputs
332 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200333 op.type = Op.Conv2DBackpropInputSwitchedBias
Louis Verhaard69b84802020-12-16 12:02:28 +0100334 op.ifm.resampling_mode = resampling_mode.TRANSPOSE
Jacob Bohlincf7da102020-05-20 09:03:40 +0200335
336 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100337 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100338
339 return op
340
341
Charles Xu9a03fdf2020-07-02 15:12:40 +0200342# Convert the op to an elementwise add
343def convert_resizebilinear_1x1_to_add(op):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200344 op.type = Op.Add
Charles Xu9a03fdf2020-07-02 15:12:40 +0200345 op.name = op.name + "_add"
Charles Xu9a03fdf2020-07-02 15:12:40 +0200346 op.attrs["resizebilinear"] = True
347 # Create an input tensor filled with zeros
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100348 shape = op.ofm_shapes[0].as_list()
Charles Xu9a03fdf2020-07-02 15:12:40 +0200349 tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add")
350 tens.values = np.zeros(shape)
351 tens.quant_values = np.zeros(shape, np.uint8)
352 tens.quantization = QuantizationParameters(0.0, 255.0)
353 tens.quantization.scale_f32 = 1.0
354 tens.quantization.zero_point = 0
355 tens.consumer_list = [op]
356 tens_op = op.inputs[1].ops[0]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100357 tens_op.set_output_tensor(tens)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200358 # Set the add inputs
359 op.inputs[1] = op.inputs[0]
360 op.inputs[0] = tens
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000361 op.set_ifm_ofm_shapes()
Charles Xu9a03fdf2020-07-02 15:12:40 +0200362
363 return op
364
365
Charles Xu87c13502020-08-06 12:17:26 +0200366# Convert ResizeBilinear to a number of 2x2 pool ops
367def convert_resizebilinear_to_2x2_pool(op):
368 count = 0
369 pre_op = op
370 outputs = op.outputs
371
372 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
373 if op.attrs["align_corners"]:
374 shape_modifier = 1
Michael McGeagh16895482020-12-14 15:51:20 +0000375 op.attrs["padding"] = Padding.VALID
Charles Xu87c13502020-08-06 12:17:26 +0200376 else:
377 shape_modifier = 0
Michael McGeagh16895482020-12-14 15:51:20 +0000378 op.attrs["padding"] = Padding.SAME
Charles Xu87c13502020-08-06 12:17:26 +0200379 op.inputs[0].resampling_mode = resampling_mode.NEAREST
380
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100381 upscaled_shape = np.array(op.ifm_shapes[0].get_hw_as_list())
382 out_shape = np.array(op.ofm_shapes[0].get_hw_as_list())
Charles Xu87c13502020-08-06 12:17:26 +0200383 if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all():
384 return op
385
386 while (upscaled_shape < out_shape).all():
387 if count == 0:
388 scaled_op = pre_op
389 else:
390 scaled_op = op.clone("_{}".format(count))
391 scaled_op.inputs[0] = pre_op.outputs[0]
392
393 upscaled_shape = upscaled_shape * 2 - shape_modifier
394
395 if (upscaled_shape == out_shape).all():
396 scaled_op.outputs = outputs
397 scaled_op.outputs[0].ops = [scaled_op]
398 else:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100399 shape = op.ofm_shapes[0].as_list()
400 shape[1:3] = upscaled_shape
Charles Xu87c13502020-08-06 12:17:26 +0200401 out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count))
402 out_tens.quantization = op.outputs[0].quantization.clone()
403 out_tens.quantization.quant_min = np.iinfo(np.int16).min
404 out_tens.quantization.quant_max = np.iinfo(np.int16).max
405 scaled_op.set_output_tensor(out_tens)
406 pre_op = scaled_op
407 count += 1
408
409 # Setup the scale value
410 if scaled_op.inputs[0].dtype.bits == 8 and scaled_op.outputs[0].dtype.bits == 16:
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100411 scaled_op.rescale = 128
Charles Xu87c13502020-08-06 12:17:26 +0200412 elif scaled_op.inputs[0].dtype.bits == 16 and scaled_op.outputs[0].dtype.bits == 8:
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100413 scaled_op.rescale = 1 / 128
414 else:
415 scaled_op.rescale = None
Patrik Gustavssoncc6915c2020-12-22 09:16:50 +0100416 scaled_op.set_ifm_ofm_shapes()
Charles Xu87c13502020-08-06 12:17:26 +0200417
418 return op
419
420
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200421def fixup_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200422 if op.type == Op.ResizeBilinear and op.run_on_npu:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100423 if op.ifm_shapes[0] == op.ofm_shapes[0]:
Charles Xu36ffaf32020-08-05 15:40:44 +0200424 # Bypass nop resizebilinear
425 op.inputs = op.inputs[:1]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200426 op.type = Op.Identity
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100427 elif op.ifm_shapes[0].height == 1 and op.ifm_shapes[0].width == 1:
Charles Xu87c13502020-08-06 12:17:26 +0200428 convert_resizebilinear_1x1_to_add(op)
429 else:
430 convert_resizebilinear_to_2x2_pool(op)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200431
432 return op
433
434
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200435def convert_nop_split_to_identity(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200436 if op.type == Op.Split and op.attrs.get("num_splits") == 1:
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200437 # the list comprehension should return a list with a single tensor
438 # if it shouldn't, remove_passthrough_tensor will fail appropriately
439 op.inputs = [i for i in op.inputs if i.shape == op.outputs[0].shape]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200440 op.type = Op.Identity
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200441 return op
442
443
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100444def rewrite_fully_connected_input(op, arch, nng):
445 if op.type == Op.FullyConnected:
446 n_in_elems = op.weights.shape[-2]
447 elms = op.ifm.elements()
448 batch_size = elms // n_in_elems
449 assert batch_size * n_in_elems == elms
450
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100451 op.ifm_shapes[0] = Shape4D([batch_size, 1, 1, n_in_elems])
Patrik Gustavssonda2b0032021-02-04 16:28:29 +0100452 if Shape4D(op.ifm.shape) != op.ifm_shapes[0]:
453 op.ifm.avoid_NHCWB16 = True
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100454 return op
455
456
Diqing Zhong94457b12020-12-09 15:22:40 +0100457def convert_batched_fc_shape(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200458 if op.type == Op.FullyConnected:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100459 # Check if the first dimension indicates batching
460 if op.ifm_shapes[0].batch > 1:
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200461 batching_split = {4: (2, 2), 8: (2, 4), 16: (4, 4)}
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100462 n = op.ifm_shapes[0].batch
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200463 h, w = batching_split.get(n, (1, n))
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100464 op.ifm_shapes[0] = Shape4D([1, h, w, op.ifm_shapes[0].depth])
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200465
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100466 op.ifm.avoid_NHCWB16 = True
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200467
468 # Reshape Weights to be 4D. IO becomes HWIO
469 weight_tensor = op.inputs[1]
470 weight_tensor.quant_values = np.expand_dims(np.expand_dims(weight_tensor.quant_values, axis=0), axis=0)
471 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
472
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100473 n = op.ofm_shapes[0].batch
474 h, w = batching_split.get(n, (1, n))
475 op.ofm_shapes[0] = Shape4D([1, h, w, op.ofm_shapes[0].depth])
476 op.ofm.avoid_NHCWB16 = True
Tim Hall79d07d22020-04-27 18:20:16 +0100477 return op
478
479
Patrik Gustavsson7bada402021-01-28 15:46:21 +0100480def unfuse_activation_function(op):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200481 if op.type == Op.ConcatTFLite and op.run_on_npu and op.activation is not None:
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100482 act_op = Operation(op.activation.op_type, op.name + op.activation.op_type.name)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200483 op.activation = None
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200484 out_tens = op.outputs[0]
485 intermediate_tens = out_tens.clone("_act_intermediate")
486 act_op.set_output_tensor(out_tens)
487 act_op.add_input_tensor(intermediate_tens)
488 op.set_output_tensor(intermediate_tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000489 act_op.set_ifm_ofm_shapes()
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200490
Louis Verhaard8912c532020-09-30 12:11:49 +0200491
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100492def rewrite_stridedslice_output(op, arch, nng):
493 if not op.run_on_npu or op.type != Op.StridedSlice:
494 return op
495
496 new_axis_mask = op.attrs["new_axis_mask"]
497 shrink_axis_mask = op.attrs["shrink_axis_mask"]
498
499 if shrink_axis_mask == 0 and new_axis_mask == 0:
500 return op
501
502 axis_4D = [0] * len(op.outputs)
503 for idx, out_tens in enumerate(op.outputs):
504 output_shape = list(out_tens.shape)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100505
Dwight Lidman73320a42020-11-05 10:34:41 +0100506 if shrink_axis_mask != 0:
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100507 n = 0
508 axis = 0
509 while shrink_axis_mask:
510 prev_mask = shrink_axis_mask
511 n += 1
512 shrink_axis_mask &= shrink_axis_mask - 1
513 axis = int(math.log2(prev_mask - shrink_axis_mask))
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100514 output_shape = output_shape[:axis] + [1] + output_shape[axis:]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100515
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100516 assert len(out_tens.shape) == (len(op.inputs[0].shape) - n)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100517 op.attrs["shrink_axis_mask"] = 0
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100518 if axis >= 0:
519 axis_4D[idx] = axis + (4 - len(output_shape))
520 else:
521 axis_4D[idx] = axis
522 op.ofm_shapes[idx] = Shape4D(output_shape)
523
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100524 elif new_axis_mask != 0:
525 n = 0
526 axis = 0
527 while new_axis_mask:
528 prev_mask = new_axis_mask
529 n += 1
530 new_axis_mask &= new_axis_mask - 1
531 axis = int(math.log2(prev_mask - new_axis_mask))
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100532 output_shape = output_shape[:axis] + output_shape[(axis + 1) :]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100533 new_axis_mask >>= 1
534
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100535 assert len(out_tens.shape) == (len(op.inputs[0].shape) + n)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100536 op.attrs["new_axis_mask"] = 0
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100537 if axis >= 0:
538 axis_4D[idx] = axis + (4 - len(output_shape))
539 else:
540 axis_4D[idx] = axis
541 op.ofm_shapes[idx] = Shape4D(output_shape)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100542
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100543 if op.ofm_shapes[idx] != Shape4D(out_tens.shape):
544 out_tens.avoid_NHCWB16 = True
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100545
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100546 op.attrs["split_axis_4D"] = axis_4D
547 return op
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100548
549
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100550def rewrite_unpack_output(op, arch, nng):
551 tens = op.outputs[0]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100552 if op.run_on_npu and op.type == Op.Unpack:
Tim Hall79d07d22020-04-27 18:20:16 +0100553 # Unpack is also referred to as Unstack
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100554 axis = int(op.attrs["axis"])
555 op.type = Op.UnpackReshaped
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100556 desired_output_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100557
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100558 if axis >= 0:
559 axis_4D = axis + (4 - len(desired_output_shape))
560 else:
561 axis_4D = axis
Tim Hall79d07d22020-04-27 18:20:16 +0100562
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100563 axis_4D_list = [0] * len(op.outputs)
Tim Hall79d07d22020-04-27 18:20:16 +0100564 for idx, out_tens in enumerate(op.outputs):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100565 op.ofm_shapes[idx] = Shape4D(desired_output_shape)
566 axis_4D_list[idx] = axis_4D
567 if op.ofm_shapes[idx] != Shape4D(out_tens.shape):
568 out_tens.avoid_NHCWB16 = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100569
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100570 op.attrs["split_axis_4D"] = axis_4D_list
571 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100572
573
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200574def add_padding_fields(op, arch, nng):
Jacob Bohlin90033f32020-08-28 15:45:44 +0200575 if op.run_on_npu:
576 if "padding" in op.attrs:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100577 input_shape = op.ifm_shapes[0]
578 output_shape = op.ofm_shapes[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200579 if op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op():
Jacob Bohlin90033f32020-08-28 15:45:44 +0200580 kernel_size = op.inputs[1].shape[:2]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200581 elif op.type.is_pool_op() or op.type.npu_block_type == NpuBlockType.ReduceSum:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200582 kernel_size = op.attrs["ksize"][1:3]
Jacob Bohlin90033f32020-08-28 15:45:44 +0200583 else:
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000584 raise UnsupportedFeatureError(f"Unknown operation that uses padding: {optype_to_builtintype(op.type)}")
Tim Hall79d07d22020-04-27 18:20:16 +0100585
Louis Verhaardaee5d752020-09-30 09:01:52 +0200586 if op.type == Op.Conv2DBackpropInputSwitchedBias:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100587 upscaling_factor = output_shape.height // input_shape.height
Jacob Bohlin90033f32020-08-28 15:45:44 +0200588 padding, skirt = calc_upscaled_padding_and_skirt(
589 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
590 )
591 else:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200592 padding, skirt = calc_padding_and_skirt(
Louis Verhaardebf4af62021-01-27 15:57:57 +0100593 op.attrs["padding"], op.kernel, input_shape, op.attrs.get("explicit_padding"),
Jacob Bohlin90033f32020-08-28 15:45:44 +0200594 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200595
Jacob Bohlin90033f32020-08-28 15:45:44 +0200596 op.attrs["explicit_padding"] = padding
597 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200598
Tim Hall79d07d22020-04-27 18:20:16 +0100599 return op
600
601
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200602def convert_depthwise_to_conv(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100603 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
604 # the ofm depth equals the depth multipler.
605 # If those conditions are true, then we can perform a simple
606 # switch of the operator type (and weight order)
607
Louis Verhaardaee5d752020-09-30 09:01:52 +0200608 if op.type == Op.DepthwiseConv2DBias and (op.attrs["depth_multiplier"] != 1):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100609 ifm_shape = op.ifm_shapes[0]
Tim Hall79d07d22020-04-27 18:20:16 +0100610 weight_tensor = op.inputs[1]
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100611 ofm_shape = op.ofm_shapes[0]
612 if (ifm_shape.depth == 1) and (ofm_shape.depth == op.attrs["depth_multiplier"]):
Tim Hall79d07d22020-04-27 18:20:16 +0100613 # Change op type to Conv2d
Louis Verhaardaee5d752020-09-30 09:01:52 +0200614 op.type = Op.Conv2DBias
Tim Hall79d07d22020-04-27 18:20:16 +0100615 del op.attrs["channel_multiplier"]
616 del op.attrs["depth_multiplier"]
617
618 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100619 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100620 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200621 raise UnsupportedFeatureError(
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000622 f"Unsupported 'DEPTHWISE_CONV_2D' with depth_multiplier = {op.attrs['depth_multiplier']},",
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100623 f" ifm channels = {ifm_shape.depth}, ofm channels = {ofm_shape.depth}",
Tim Hall79d07d22020-04-27 18:20:16 +0100624 )
Tim Halle6ccd872020-11-09 16:46:37 +0000625 DebugDatabase.add_optimised(op, op)
Tim Hall79d07d22020-04-27 18:20:16 +0100626 return op
627
628
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200629def reorder_depthwise_weights(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200630 if op.type.is_depthwise_conv2d_op():
Jacob Bohline843d332020-06-23 12:12:56 +0200631 weight_tensor = op.inputs[1]
632 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100633 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200634 weight_tensor.weight_transpose_depthwise = True
635
636 return op
637
638
Diqing Zhong016b8272020-12-16 16:46:06 +0100639def optimise_strided_conv(op, arch, nng):
640 stride_x, stride_y = op.get_kernel_stride()
641 ifm_tensor, _, weight_tensor, _ = op.get_ifm_ifm2_weights_ofm()
642
643 if (
644 op.type == Op.Conv2DBias
645 and op.op_index == 0
646 and stride_x == 2
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100647 and op.ifm_shapes[0].depth <= 4
648 and op.ifm_shapes[0].width % 2 == 0
Diqing Zhong016b8272020-12-16 16:46:06 +0100649 and weight_tensor is not None
650 and weight_tensor.shape[1] >= 2
651 ):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100652 ifm_shape = op.ifm_shapes[0]
Diqing Zhong016b8272020-12-16 16:46:06 +0100653 # IFM
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100654 op.ifm_shapes[0] = Shape4D([ifm_shape.batch, ifm_shape.height, ifm_shape.width // 2, ifm_shape.depth * 2])
655 op.ifm.avoid_NHCWB16 = True
Diqing Zhong016b8272020-12-16 16:46:06 +0100656
657 # Weights
658 weight_shape = weight_tensor.shape
659 if weight_shape[1] % 2 != 0:
660 weight_shape[1] = weight_shape[1] + 1
661 padded_array = np.zeros(weight_shape)
662 for i in range(weight_shape[0]):
663 padded_array[i] = np.vstack(
664 [
665 weight_tensor.quant_values[i],
666 np.full((1, weight_shape[2], weight_shape[3]), weight_tensor.quantization.zero_point),
667 ]
668 )
669 weight_tensor.quant_values = padded_array
670 weight_shape[1] //= 2
671 weight_shape[2] *= 2
672 weight_tensor.quant_values = np.reshape(weight_tensor.quant_values, weight_shape)
673 weight_tensor.set_all_shapes(weight_shape)
674 # If multiple copies of the weights are used, we could avoid
675 # them having the same address by changing the value_id
676 weight_tensor.value_id = uuid.uuid4()
677
678 # Strides
679 stride_x = 1
680 op.attrs.update({"stride_w": stride_x, "stride_h": stride_y, "strides": (1, stride_y, stride_x, 1)})
681
Diqing Zhong016b8272020-12-16 16:46:06 +0100682 return op
683
684
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200685def convert_conv_to_fc(op, arch, nng):
Michael McGeagh8d939c02020-07-29 13:11:43 +0100686 # Conv 1x1 can be equivalent to Fully Connected.
687 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
688 # caching/double buffering for the weights.
689 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200690 if op.type == Op.Conv2DBias:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000691 h = op.ifm_shapes[0].height
692 w = op.ifm_shapes[0].width
Michael McGeagh8d939c02020-07-29 13:11:43 +0100693 kh, kw, _, _ = op.inputs[1].shape
694 if h == 1 and w == 1 and kh == 1 and kw == 1:
695 # Overwrite this op as a Fully Connected Op
696 op.name += "_fc"
Louis Verhaardaee5d752020-09-30 09:01:52 +0200697 op.type = Op.FullyConnected
Michael McGeagh8d939c02020-07-29 13:11:43 +0100698 op.attrs = {
Michael McGeagh8d939c02020-07-29 13:11:43 +0100699 "weights_format": 0,
Michael McGeagh8d939c02020-07-29 13:11:43 +0100700 }
701 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
702 weight_tensor = op.inputs[1]
703 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
704 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100705
Tim Halle6ccd872020-11-09 16:46:37 +0000706 DebugDatabase.add_optimised(op, op)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100707 return op
708
709
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200710def fixup_relus_with_differing_ifm_ofm_scaling(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200711 if op.run_on_npu and op.type.is_relu_op():
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100712 ifm = op.inputs[0]
713 ofm = op.outputs[0]
714 # Relu with differing IFM and OFM scaling cannot be fused with another primary op
715 # and requires its own to be inserted
Tim Hall93582962020-09-09 21:58:15 +0100716 if not check_quantized_tens_scaling_equal(ifm, ofm):
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100717 # Override this op with its own primary op (avgpool)
718 relu_fused_op = create_avgpool_nop(op.name + "_avgpool")
719 # And fuse the original activation function to it
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100720 relu_fused_op.activation = create_activation_function(op.type)
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100721 # Tidy up and assign the ifm and ofm to the new op
722 ifm.consumer_list.remove(op)
Andreas Nevalainenf3d737e2020-09-25 14:12:43 +0200723
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100724 relu_fused_op.add_input_tensor(ifm)
725 relu_fused_op.set_output_tensor(ofm)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000726 relu_fused_op.set_ifm_ofm_shapes()
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100727 op = relu_fused_op
728 return op
729
730
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200731def fixup_elementwise_with_scalars(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200732 if op.type.is_binary_elementwise_op():
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200733 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200734 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
735 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
736 if diff > 0:
737 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
738 elif diff < 0:
739 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200740 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
741 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
742 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
743 ifm_tensor.storage_shape = ifm_tensor.shape
744 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
745 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
746 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
747 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200748 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100749
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200750
Tim Hall4e127762020-05-15 16:05:49 +0100751# Set input/output tensor equivalence to the same id for memory operations
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200752def set_tensor_equivalence(op, arch, nng):
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100753 if op.type in memory_only_ops:
Tim Hall4e127762020-05-15 16:05:49 +0100754 eid = op.outputs[0].equivalence_id
755 for inp in op.inputs:
756 inp.equivalence_id = eid
757 return op
758
759
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100760def set_ifm_ofm_op_shapes(op, arch, nng):
761 if op.run_on_npu and op.type.needs_shapes():
762 if op.ifm_shapes or op.ofm_shapes:
763 # Shapes already set
764 return op
765 op.set_ifm_ofm_shapes()
766 return op
767
768
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200769def convert_softmax(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200770 if op.type == Op.Softmax and op.run_on_npu:
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200771 softmax = SoftMax(op)
772 op = softmax.get_graph()
773 return op
774
775
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200776def convert_mul_max_to_abs_or_lrelu(op, arch, nng):
Diego Russoea6111a2020-04-14 18:41:58 +0100777 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100778
779 Input X For X = -1 or X > 0
780 | \ / This subgraph can be replaced with either
781 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
782 | /
783 Max
784 """
785
Louis Verhaardaee5d752020-09-30 09:01:52 +0200786 if op.type == Op.Maximum:
Tim Hall79d07d22020-04-27 18:20:16 +0100787 # finds the Mul input(s) to the Max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200788 muls = [i for i in op.inputs if i.ops[0].type == Op.Mul]
Tim Hall79d07d22020-04-27 18:20:16 +0100789 if len(muls) == 1:
790 mul = muls[0].ops[0]
791 elif len(muls) == 2:
792 # In the case both inputs are Muls, find the one with the same input as the Max
793 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
794 else:
795 # No Mul inputs
796 return op
797
798 # make sure the Mul doesn't have any other consumers
Louis Verhaardd7911c42020-08-25 13:36:41 +0200799 mul_ofm = mul.outputs[0]
800 if len(mul_ofm.consumers()) != 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100801 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200802 # make sure the Mul doesn't have a fused activation function
803 if mul.activation:
Tim Hall79d07d22020-04-27 18:20:16 +0100804 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200805 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100806 if ifm is None or ofm is None:
807 return op
808
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200809 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
810 return op
Tim Hall93582962020-09-09 21:58:15 +0100811 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 +0200812 # rewrite to LeakyRelu currently only makes sense if the quantization is identical
813 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100814
815 # finds the branched input that goes to both the Max and the Mul
816 shared = set(op.inputs) & set(mul.inputs)
817 if len(shared) == 1:
818 shared_in = shared.pop()
819 # find the constant scalar input to the Mul
820 const_tens = (set(mul.inputs) - {shared_in}).pop()
821 # check that it is a scalar
822 if const_tens.shape != []:
823 return op
824 const = const_tens.ops[0]
825 # check that it is a constant
Louis Verhaardaee5d752020-09-30 09:01:52 +0200826 if const.type != Op.Const:
Tim Hall79d07d22020-04-27 18:20:16 +0100827 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200828 # Remove the Mul from the shared input's consumers
829 shared_in.consumer_list.remove(mul)
Tim Hall79d07d22020-04-27 18:20:16 +0100830 else:
831 return op
832
833 val = const.outputs[0].values
834 if val >= 0:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200835 new_op = Op.LeakyRelu
Tim Hall79d07d22020-04-27 18:20:16 +0100836 op.attrs["alpha"] = val
Louis Verhaardd7911c42020-08-25 13:36:41 +0200837 # to produce bit exact results, the alpha is not enough;
838 # save additional scaling info in attr "alpha_scale", to be used as input
839 # to the LUT construction
840 alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point
841 mul_ifm_scale = np.double(ifm.quantization.scale_f32)
842 mul_ifm2_scale = np.double(const_tens.quantization.scale_f32)
843 mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32)
844 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale)
845 op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift)
Tim Hall79d07d22020-04-27 18:20:16 +0100846 elif val == -1:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200847 new_op = Op.Abs
Tim Hall79d07d22020-04-27 18:20:16 +0100848 else:
849 return op
850
Louis Verhaardaee5d752020-09-30 09:01:52 +0200851 op.type = new_op
852 op.name = op.name.replace("Maximum", new_op.name)
853 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100854 op.inputs = [shared_in]
Patrik Gustavssonc509d332020-12-22 13:53:52 +0100855 op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000856
857 # Record optimisation in debug database
858 DebugDatabase.add_optimised(op, op)
859
Tim Hall79d07d22020-04-27 18:20:16 +0100860 return op
861
862
Diqing Zhong189f7482021-01-26 12:12:51 +0100863def convert_hardswish_to_lut(op, arch, nng):
864 if op.type == Op.HardSwish:
865 ifm, ofm = op.get_ifm_ofm()
866 # Generate the LUT
867 ifm_scale = np.double(ifm.quantization.scale_f32)
868 ofm_scale = np.double(ofm.quantization.scale_f32)
869 zp_in = ifm.quantization.zero_point
870 zp_out = ofm.quantization.zero_point
871 ifm_scale_hires = (1 / 128) * ifm_scale
872 relu_multiplier = np.double(3 / 32768)
873 out_scale, out_shift = scaling.quantise_scale(ifm_scale_hires / ofm_scale)
874 relu_scale, relu_shift = scaling.quantise_scale(ifm_scale_hires / relu_multiplier)
875 # Use 16bit scale
876 out_scale_16 = fp_math.downscale_multiplier_int32_to_int16(out_scale)
877 relu_scale_16 = fp_math.downscale_multiplier_int32_to_int16(relu_scale)
878
879 values = []
880 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
881 quantized_min = min(ix)
882 quantized_max = max(ix)
883 for x in ix:
884 input_value = x - zp_in
885 input_value_hires = input_value * 128
886 # Compute the input value on essentially the output scale, not shifted yet
887 input_value_preshift = fp_math.saturating_rounding_mul16(input_value_hires, out_scale_16)
888 # Compute the "relu-ish multiplier". This matches the code in TensorFlow Lite Micro kernel
889 relu_value = np.int16(input_value_hires)
890 if relu_shift < 31:
891 relu_value = fp_math.shift_left16(relu_value, 30 - relu_shift)
892
893 relu_value = fp_math.saturating_rounding_mul16(relu_value, relu_scale_16)
894
895 if relu_shift < 31:
896 relu_value = fp_math.shift_left16(relu_value, 1)
897
898 if relu_shift > 31:
899 relu_value = fp_math.rounding_divide_by_pot(relu_value, relu_shift - 31)
900
901 # Rescaled the value into a 16bit fixedpoint relu_value in [-1, 1]
902 # Now convert that to a 16bit fixedpoint value in [0, 1]
903 relu_value = (relu_value + (1 << 15)) >> 1
904 lut_result = fp_math.saturating_mul16(relu_value, input_value_preshift)
905 shift = 31 - out_shift
906 shift = -shift if shift < 0 else 0
907 # Finally apply the output shift
908 lut_result = fp_math.rounding_divide_by_pot(lut_result, shift) + zp_out
909 lut_result = min(quantized_max, max(quantized_min, lut_result))
910 values.append(lut_result)
911 return convert_to_lut(op, values, "hardswish")
912 return op
913
914
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200915def convert_lrelu_to_mul_max(op, arch):
916 # Converts LeakyRelu to Max(alpha * IFM, identity * IFM)
917 # (the opposite of convert_mul_max_to_abs_or_lrelu)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200918 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100919 if ifm is None or ofm is None:
920 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200921
922 # Add multiplication with alpha
Louis Verhaardaee5d752020-09-30 09:01:52 +0200923 mul_alpha = Operation(Op.Mul, op.name + "_mul_alpha")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200924 mul_alpha.add_input_tensor(ifm)
925 # Create const tensor containing alpha as scalar
926 alpha = op.attrs["alpha"]
927 quantization = ifm.quantization.clone()
928 quantization.min = 0
929 quantization.max = alpha * (quantization.quant_max - quantization.quant_min)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200930 quantization.zero_point = 0
Louis Verhaardece4e652021-01-07 13:35:47 +0100931 if np.isinf(1 / np.float32(alpha)):
932 # Handling of alpha near zero
933 quantization.scale_f32 = 1
934 scalar = 0
935 else:
936 quantization.scale_f32 = alpha
937 scalar = 1
938 alpha_tens = create_const_tensor(
939 op.name + "_alpha_scalar", [], ifm.dtype, [scalar], np.int8, quantization=quantization
940 )
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200941 mul_alpha.add_input_tensor(alpha_tens)
942 fm_alpha = ofm.clone(op.name + "_alpha")
943 mul_alpha.set_output_tensor(fm_alpha)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000944 mul_alpha.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000945 DebugDatabase.add_optimised(op, mul_alpha)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200946
Tim Hall93582962020-09-09 21:58:15 +0100947 if check_quantized_tens_scaling_equal(ifm, ofm):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200948 # No identity multiplication is needed
949 fm_id = ifm
950 else:
951 # Add multiplication with identity
Louis Verhaardaee5d752020-09-30 09:01:52 +0200952 mul_identity = Operation(Op.Mul, op.name + "_mul_identity")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200953 mul_identity.add_input_tensor(ifm)
954 # Create const tensor containing identity as scalar
955 quantization = ifm.quantization.clone()
956 quantization.min = 0
957 quantization.max = quantization.quant_max - quantization.quant_min
958 quantization.scale_f32 = 1
959 quantization.zero_point = 0
960 identity_tens = create_const_tensor(
961 op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization
962 )
963 mul_identity.add_input_tensor(identity_tens)
Louis Verhaardece4e652021-01-07 13:35:47 +0100964 # Make sure that fm_id is allocated to a different address than fm_alpha
965 fm_id = ofm.clone(op.name + "_id", set_unique=True)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200966 mul_identity.set_output_tensor(fm_id)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000967 mul_identity.set_ifm_ofm_shapes()
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100968 DebugDatabase.add_optimised(op, mul_identity)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200969
970 # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs
Louis Verhaardaee5d752020-09-30 09:01:52 +0200971 op.type = Op.Maximum
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200972 op.name = op.name.replace("LeakyRelu", "Maximum")
973 op.inputs = []
974 ifm.consumer_list.remove(op)
975 op.add_input_tensor(fm_alpha)
976 op.add_input_tensor(fm_id)
Patrik Gustavssonc509d332020-12-22 13:53:52 +0100977 op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000978
979 DebugDatabase.add_optimised(op, op)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200980 return op
981
982
Louis Verhaard2e186c72020-10-09 10:47:04 +0200983def convert_to_lut(op, lut_values, lut_name):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200984 # Rewrite the operation by Add with scalar 0 + LUT activation
985 ifm = op.inputs[0]
Tim Hall93582962020-09-09 21:58:15 +0100986 if ifm is None:
987 return op
Louis Verhaard58520b92020-08-24 16:45:38 +0200988 assert ifm.dtype.size_in_bytes() == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +0200989 op.type = Op.Add
Louis Verhaard2e186c72020-10-09 10:47:04 +0200990 op.name = op.name + "_lut_" + lut_name
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200991 # Mark as no-op to enable potential fusing optimizations
992 op.attrs["is_nop"] = True
993 # Create an input tensor containing scalar zero
994 quantization = QuantizationParameters(0.0, 255.0)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200995 quantization.scale_f32 = ifm.quantization.scale_f32
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200996 quantization.zero_point = 0
Louis Verhaard2e186c72020-10-09 10:47:04 +0200997 tens = create_const_tensor(op.inputs[0].name + "_scalar0", [], ifm.dtype, [0], np.uint8, quantization=quantization)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200998 op.add_input_tensor(tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000999 op.ifm_shapes.append(Shape4D(tens.shape))
Patrik Gustavsson2349d422020-12-01 16:02:29 +01001000
Louis Verhaardf03bad32020-09-25 08:30:44 +02001001 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
1002 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
1003 # should be the same as the IFM
Louis Verhaardaee5d752020-09-30 09:01:52 +02001004 op.forced_output_quantization = ifm.quantization
Louis Verhaard2e186c72020-10-09 10:47:04 +02001005 lut_tensor = lut.create_lut_tensor(op.name + "_values", lut_values, DataType.int8)
Louis Verhaardf03bad32020-09-25 08:30:44 +02001006 op.set_activation_lut(lut_tensor)
Patrik Gustavssonc509d332020-12-22 13:53:52 +01001007 op.set_ifm_ofm_shapes()
Louis Verhaardf03bad32020-09-25 08:30:44 +02001008 return op
1009
1010
Louis Verhaard2e186c72020-10-09 10:47:04 +02001011def convert_to_lut8(op, fn, fn_name):
Louis Verhaardf03bad32020-09-25 08:30:44 +02001012 # Converts op to a no-op + int8/uint8 LUT which is generated with the given function.
1013 # fn is a function(real) -> real
Louis Verhaardaee5d752020-09-30 09:01:52 +02001014 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardf03bad32020-09-25 08:30:44 +02001015 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
1016 return op
1017 # Generate the LUT
1018 ifm_scale = np.double(ifm.quantization.scale_f32)
1019 ofm_scale = np.double(ofm.quantization.scale_f32)
1020 zp_in = ifm.quantization.zero_point
1021 zp_out = ofm.quantization.zero_point
1022 values = []
1023 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
1024 quantized_min = min(ix)
1025 quantized_max = max(ix)
1026 for x in ix:
1027 x_real = ifm_scale * (x - zp_in)
1028 y_real = fn(x_real)
1029 lut_result = round_away_zero(zp_out + y_real / ofm_scale)
1030 lut_result = min(quantized_max, max(quantized_min, lut_result))
1031 values.append(lut_result)
Louis Verhaard2e186c72020-10-09 10:47:04 +02001032 return convert_to_lut(op, values, fn_name)
Louis Verhaardf03bad32020-09-25 08:30:44 +02001033
1034
1035def convert_lrelu_to_lut(op, arch):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001036 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001037 # Generate the LUT
Louis Verhaardd7911c42020-08-25 13:36:41 +02001038 alpha = op.attrs["alpha"]
1039 ifm_scale = np.double(ifm.quantization.scale_f32)
1040 ofm_scale = np.double(ofm.quantization.scale_f32)
1041 zp_in = ifm.quantization.zero_point
1042 zp_out = ofm.quantization.zero_point
1043 identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale)
1044 alpha_scalar = 1
1045 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale)
1046 if "alpha_scaling" in op.attrs:
1047 # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu
1048 alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"]
1049 values = []
Louis Verhaard58520b92020-08-24 16:45:38 +02001050 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
Louis Verhaardd7911c42020-08-25 13:36:41 +02001051 quantized_min = min(ix)
1052 quantized_max = max(ix)
1053 for x in ix:
1054 if x < zp_in:
1055 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(
1056 alpha_scalar * (x - zp_in), alpha_scale, alpha_shift
1057 )
1058 else:
1059 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift)
1060 lut_result = min(quantized_max, max(quantized_min, lut_result))
1061 values.append(lut_result)
Louis Verhaard2e186c72020-10-09 10:47:04 +02001062 return convert_to_lut(op, values, "lrelu")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001063
1064
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001065def convert_lrelu(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001066 # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max
Louis Verhaardaee5d752020-09-30 09:01:52 +02001067 if op.type != Op.LeakyRelu:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001068 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001069 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +01001070 if ifm is None or ofm is None:
1071 return op
Louis Verhaardd7911c42020-08-25 13:36:41 +02001072 if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype:
1073 # use LUT for int8/uint8
1074 return convert_lrelu_to_lut(op, arch)
Tim Hall93582962020-09-09 21:58:15 +01001075 if check_quantized_tens_scaling_equal(ifm, ofm) and ifm.dtype == ofm.dtype == DataType.int16:
Louis Verhaardd7911c42020-08-25 13:36:41 +02001076 # use LeakyRelu unmodified for int16 with equal input/output scaling
1077 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001078 return convert_lrelu_to_mul_max(op, arch)
1079
1080
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001081def convert_tanh_sigmoid_to_lut(op, arch, nng):
Louis Verhaardf03bad32020-09-25 08:30:44 +02001082 # Converts int8/uint8 Sigmoid and Tanh to a LUT based solution
Louis Verhaardaee5d752020-09-30 09:01:52 +02001083 if op.type == Op.Sigmoid:
Louis Verhaard2e186c72020-10-09 10:47:04 +02001084 return convert_to_lut8(op, clamp_sigmoid, "sigmoid")
Louis Verhaardaee5d752020-09-30 09:01:52 +02001085 elif op.type == Op.Tanh:
Louis Verhaard2e186c72020-10-09 10:47:04 +02001086 return convert_to_lut8(op, math.tanh, "tanh")
Louis Verhaardf03bad32020-09-25 08:30:44 +02001087 return op
1088
1089
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001090def remove_reshapes(op, arch):
1091 if op.run_on_npu and op.type == Op.Reshape:
1092 ofm = op.ofm
1093 ifm = op.ifm
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001094
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001095 # Check if quantization is the same in the input and output for the reshape ops
1096 if not check_quantized_tens_scaling_equal(ifm, ofm):
1097 # TODO Both tensors are needed, since quantisation properties currently are linked to Tensors.
1098 # In order to remove this reshape either quantization properties need to be moved to Operator,
1099 # or the reshape need to be replace with a NOP.
1100 return
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001101
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001102 # Check if Reshape ifm/ofm are network ifm/ofm
Patrik Gustavsson138d47f2021-02-08 10:13:48 +01001103 ifm_is_sg_ifm = ifm.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const)
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001104 ifm_is_sg_ofm = any(ifm_cons is None for ifm_cons in ifm.consumer_list)
1105 ofm_is_sg_ofm = any(ofm_cons is None for ofm_cons in ofm.consumer_list)
Patrik Gustavsson138d47f2021-02-08 10:13:48 +01001106 # This case should be handled prior to this function
1107 assert not ((ifm_is_sg_ifm or ifm_is_sg_ofm) and ofm_is_sg_ofm)
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001108
1109 if ofm_is_sg_ofm:
1110 # Bypassed by replacing ifm with ofm
1111 ofm.ops = []
1112 for prev_op in ifm.ops:
1113 prev_op.outputs = [ofm]
1114 ofm.ops.append(prev_op)
1115
1116 # All ifm consumers need to use ofm as input
1117 for ifm_cons in ifm.consumer_list:
1118 for ifm_idx, cons_ifm in enumerate(ifm_cons.inputs):
1119 if cons_ifm == ifm:
1120 ifm_cons.set_input_tensor(ofm, ifm_idx)
1121 if op.ifm_shapes[0] != op.ofm_shapes[0]:
1122 ofm.avoid_NHCWB16 = True
1123 else:
1124 # Bypassed Reshape by replacing ofm with ifm
1125 for cons in ofm.consumer_list:
1126 for ifm_idx, cons_ifm in enumerate(cons.inputs):
1127 if cons_ifm == ofm:
1128 cons.set_input_tensor(ifm, ifm_idx)
1129 if op.ifm_shapes[0] != op.ofm_shapes[0]:
1130 ifm.avoid_NHCWB16 = True
1131
1132
1133def check_reshapes(op, arch):
1134 if op.run_on_npu and op.type == Op.Reshape:
1135 ofm = op.ofm
1136
1137 if check_quantized_tens_scaling_equal(op.ifm, ofm):
1138 # Reshape should have been removed
1139 raise VelaError(f"Reshape op {op} expected to have been removed, still remains")
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001140
1141
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001142def fuse_activation_function_with_prev(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001143 # if op is a no-op: attempts to move the activation function to the preceding op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001144 if not op.attrs.get("is_nop", False) or op.activation is None:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001145 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001146 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +01001147 if ifm is None or ofm is None:
1148 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001149 # finds the input(s) to the operation
1150 prev_op = ifm.ops[0]
1151 # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed
1152 fuse = (
1153 prev_op.run_on_npu
Louis Verhaardaee5d752020-09-30 09:01:52 +02001154 and prev_op.type.npu_block_type != NpuBlockType.Default
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001155 and len(ifm.ops) == 1
1156 and len(prev_op.outputs[0].consumers()) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +02001157 and prev_op.activation is None
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001158 )
1159 if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0:
1160 # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC),
1161 # LUT currently only works correctly for elementwise ops
1162 fuse = False
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001163 if not fuse:
1164 return op
1165 # Move the fused activation function + corresponding info to prev_op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001166 prev_op.activation = op.activation
1167 prev_op.forced_output_quantization = op.forced_output_quantization
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001168 if op.activation_lut is not None:
1169 prev_op.set_activation_lut(op.activation_lut)
1170 # Bypass op
Louis Verhaard98a34992020-09-01 10:39:04 +02001171 prev_op.set_output_tensor(ofm)
Tim Halle6ccd872020-11-09 16:46:37 +00001172 DebugDatabase.add_optimised(op, prev_op)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001173 return op
1174
1175
Louis Verhaardae2d5532020-12-11 17:19:54 +01001176def optimise_pad(op, arch, nng):
1177 """
1178 Converts tens1 -> PAD -> tens2 -> CONV to tens1 -> CONV
1179 if both operations can be run on the NPU.
1180 """
1181 if (
1182 (op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op())
1183 and op.run_on_npu
1184 and op.attrs["padding"] == Padding.VALID
1185 ):
1186 pad_op = op.ifm.ops[0]
1187 if pad_op.type != Op.Pad or not pad_op.run_on_npu:
1188 return op
1189 # Bypass the PAD operator
1190 op.set_input_tensor(pad_op.ifm, 0)
1191 # Adjust the padding attributes of the convolution operator
1192 op.attrs["padding"] = Padding.EXPLICIT
1193 padding = pad_op.inputs[1].values # 4x2 tensor, first dimension is N, H, W, C
1194 top, left, bottom, right = (padding[1][0], padding[2][0], padding[1][1], padding[2][1])
1195 op.attrs["explicit_padding"] = (top, left, bottom, right)
1196 op.set_ifm_ofm_shapes()
1197 return op
1198
1199
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001200def add_attrs_to_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001201 if op.type == Op.ResizeBilinear and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +02001202 input_tensor = op.inputs[0]
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001203 input_shape = op.ifm_shapes[0]
1204 upscaled_height = input_shape.height * 2
1205 upscaled_width = input_shape.width * 2
1206 out_shape = op.ofm_shapes[0]
1207 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 +02001208 # this means the output is supposed to be a x2 upscale,
1209 # so we need to do SAME padding
Michael McGeagh16895482020-12-14 15:51:20 +00001210 op.attrs["padding"] = Padding.SAME
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001211 elif (
1212 op.attrs["align_corners"]
1213 and out_shape.height == (upscaled_height - 1)
1214 and out_shape.width == (upscaled_width - 1)
1215 ):
Dwight Lidman42fed942020-05-29 09:37:03 +02001216 # here we can just run the avg pool without padding and
1217 # produce a (M * 2 - 1, N * 2 - 1) sized output
Michael McGeagh16895482020-12-14 15:51:20 +00001218 op.attrs["padding"] = Padding.VALID
Dwight Lidman42fed942020-05-29 09:37:03 +02001219 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +02001220 return op
Dwight Lidman42fed942020-05-29 09:37:03 +02001221 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +01001222 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +02001223 return op
1224
1225
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001226def fixup_bias_tensors(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001227 if op.type.needs_bias() and op.bias is None:
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001228 # Op has no bias, add bias tensor filled with zeros
1229 nr_biases = op.inputs[1].shape[-1]
1230 bias_values = [0] * nr_biases
1231 bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values)
1232 bias_tensor.quant_values = bias_tensor.values
1233 op.set_input_tensor(bias_tensor, -1)
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +02001234
1235 return op
1236
1237
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001238def supported_operator_check(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +01001239 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
1240 return op
1241
1242
Tim Halle6ccd872020-11-09 16:46:37 +00001243def _record_optimised(op, arch):
1244 if op.type != Op.Const:
1245 DebugDatabase.add_optimised(op, op)
1246
1247
Tim Hall79d07d22020-04-27 18:20:16 +01001248def optimise_graph_a(nng, arch, verbose_graph=False):
1249 if verbose_graph:
1250 nng.print_graph()
1251
Patrik Gustavsson2349d422020-12-01 16:02:29 +01001252 pre_process_list = [
1253 supported_operator_check,
1254 set_ifm_ofm_op_shapes,
1255 # TODO: memory-only Op removal
1256 ]
1257
1258 for idx, sg in enumerate(nng.subgraphs):
1259 # rewrite graph pass
1260 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1261 nng, sg, arch, [], pre_process_list, rewrite_unsupported=False,
1262 )
1263
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001264 # Handle Concat Ops
1265 for idx, sg in enumerate(nng.subgraphs):
1266 # rewrite graph pass
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +01001267 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [rewrite_concat_ops])
1268 sg.refresh_after_modification()
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001269
1270 # Handle Split Ops
1271 for idx, sg in enumerate(nng.subgraphs):
1272 # rewrite graph pass
1273 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1274 nng,
1275 sg,
1276 arch,
1277 [],
1278 [rewrite_unpack_output, rewrite_stridedslice_output, convert_nop_split_to_identity],
1279 rewrite_unsupported=False,
1280 )
1281
1282 for idx, sg in enumerate(nng.subgraphs):
1283 # rewrite graph pass
1284 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1285 nng, sg, arch, [rewrite_split_ops], [], rewrite_unsupported=False,
1286 )
1287
Patrik Gustavsson138d47f2021-02-08 10:13:48 +01001288 # Handle sg input output
1289 for idx, sg in enumerate(nng.subgraphs):
1290 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1291 nng, sg, arch, [], [fix_sg_input_output], rewrite_unsupported=False,
1292 )
1293
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001294 # Removal of reshapes
1295 for sg in nng.subgraphs:
1296 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [remove_reshapes])
1297 sg.refresh_after_modification()
1298
Tim Hall79d07d22020-04-27 18:20:16 +01001299 op_rewrite_list = [
Tim Hall4e127762020-05-15 16:05:49 +01001300 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +01001301 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +01001302 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +02001303 convert_softmax,
Diqing Zhong016b8272020-12-16 16:46:06 +01001304 optimise_strided_conv,
Diqing Zhong189f7482021-01-26 12:12:51 +01001305 convert_hardswish_to_lut,
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +01001306 rewrite_fully_connected_input,
Diqing Zhong94457b12020-12-09 15:22:40 +01001307 convert_batched_fc_shape,
Tim Hall79d07d22020-04-27 18:20:16 +01001308 fixup_conv2d_backprop,
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +01001309 fixup_relus_with_differing_ifm_ofm_scaling,
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001310 fixup_elementwise_with_scalars, # TODO Move to early stage?
Jacob Bohline843d332020-06-23 12:12:56 +02001311 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +02001312 fixup_resizebilinear,
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001313 fixup_bias_tensors,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001314 convert_mul_max_to_abs_or_lrelu,
1315 convert_lrelu,
Louis Verhaardf03bad32020-09-25 08:30:44 +02001316 convert_tanh_sigmoid_to_lut,
Tim Hall79d07d22020-04-27 18:20:16 +01001317 ]
1318
1319 for idx, sg in enumerate(nng.subgraphs):
1320 # rewrite graph pass
1321 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Dwight Lidman73320a42020-11-05 10:34:41 +01001322 nng, sg, arch, [], op_rewrite_list, rewrite_unsupported=False,
Tim Hall79d07d22020-04-27 18:20:16 +01001323 )
1324
1325 for idx, sg in enumerate(nng.subgraphs):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001326 # remove passthrough tensors and attempt further optimizations
1327 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Louis Verhaardae2d5532020-12-11 17:19:54 +01001328 nng,
1329 sg,
1330 arch,
1331 [remove_passthrough_tensor],
1332 [fuse_activation_function_with_prev, optimise_pad, add_padding_fields],
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001333 )
Tim Hall79d07d22020-04-27 18:20:16 +01001334
Patrik Gustavssone3b1b912021-02-09 15:38:46 +01001335 # Removal of SplitSliceRead, need to be done after optimisation has been performed,
1336 # since ifm/ofm_shapes are of importance to this function
1337 for sg in nng.subgraphs:
1338 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [remove_SplitSliceRead])
1339 sg.refresh_after_modification()
1340
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001341 # Post-optimisation operator debug tracing, and checking that no undesired reshapes are left in the graph
Tim Halle6ccd872020-11-09 16:46:37 +00001342 for sg in nng.subgraphs:
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001343 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [check_reshapes, _record_optimised])
Tim Hall79d07d22020-04-27 18:20:16 +01001344
1345 if verbose_graph:
1346 nng.print_graph()
1347 return nng