blob: 1966a82d61aeb1fb9d9f9e9a28e63353bc44dfb3 [file] [log] [blame]
Tim Hall79d07d22020-04-27 18:20:16 +01001# Copyright (C) 2020 Arm Limited or its affiliates. All rights reserved.
2#
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the License); you may
6# not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an AS IS BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
Tim Hall79d07d22020-04-27 18:20:16 +010016# Description:
17# Early optimisation of the network graph, using the rewrite_graph module to do the traversal of the graph. These are
18# split into two parts optimise_graph_a and optimise_graph_b.
Tim Hall79d07d22020-04-27 18:20:16 +010019import math
Diego Russoea6111a2020-04-14 18:41:58 +010020
21import numpy as np
22
Louis Verhaardd7911c42020-08-25 13:36:41 +020023from . import fp_math
Louis Verhaardb9fc33c2020-08-13 11:47:36 +020024from . import lut
Diego Russoea6111a2020-04-14 18:41:58 +010025from . import rewrite_graph
Louis Verhaardd7911c42020-08-25 13:36:41 +020026from . import scaling
Diego Russoea6111a2020-04-14 18:41:58 +010027from .data_type import DataType
Louis Verhaard7db78962020-05-25 15:05:26 +020028from .errors import UnsupportedFeatureError
Dwight Lidman42fed942020-05-29 09:37:03 +020029from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Louis Verhaard8912c532020-09-30 12:11:49 +020030from .numeric_util import clamp_sigmoid
Louis Verhaarde0ef2732020-06-03 08:56:44 +020031from .numeric_util import full_shape
Louis Verhaardf03bad32020-09-25 08:30:44 +020032from .numeric_util import round_away_zero
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +010033from .operation import create_avgpool_nop
Diego Russoe8a10452020-04-21 17:39:10 +010034from .operation import NpuBlockType
Louis Verhaardaee5d752020-09-30 09:01:52 +020035from .operation import Op
Diego Russoe8a10452020-04-21 17:39:10 +010036from .operation import Operation
Fredrik Svedberga0c36242020-06-03 15:43:31 +020037from .softmax import SoftMax
Michael McGeaghc5b549b2020-08-07 11:54:28 +010038from .tensor import create_const_tensor
39from .tensor import create_reshape_tensor
Charles Xu9a03fdf2020-07-02 15:12:40 +020040from .tensor import QuantizationParameters
Diego Russoe8a10452020-04-21 17:39:10 +010041from .tensor import Tensor
Tim Hall79d07d22020-04-27 18:20:16 +010042
Louis Verhaardaee5d752020-09-30 09:01:52 +020043passthrough_nodes = set((Op.Identity,))
Tim Hall79d07d22020-04-27 18:20:16 +010044
Louis Verhaardaee5d752020-09-30 09:01:52 +020045memory_only_ops = set((Op.Reshape,))
Michael McGeagh11b0bdb2020-09-08 11:07:35 +010046
Tim Hall79d07d22020-04-27 18:20:16 +010047
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +020048def remove_passthrough_tensor(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +010049 if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes:
50 assert len(tens.ops[0].inputs) == 1
51 tens = tens.ops[0].inputs[0]
52 return tens
53
54
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +020055def rewrite_concat(tens, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +020056 if len(tens.ops) == 1 and tens.ops[0].type.is_concat_op():
Tim Hall79d07d22020-04-27 18:20:16 +010057 concat_op = tens.ops[0]
58 if tens != concat_op.outputs[0]:
59 return tens # don't attempt to rewrite the min/max outputs of QuantizedConcat
60
61 # Not supported so leave it and run on CPU
62 if not concat_op.run_on_npu:
63 return tens
64
65 inputs, axis = concat_op.get_concat_inputs_axis()
66
67 tens.ops = []
68 offset = 0
69 for idx, inp in enumerate(inputs):
Louis Verhaardaee5d752020-09-30 09:01:52 +020070 new_op = Operation(Op.ConcatSliceWrite, concat_op.name + str(idx))
Tim Hall79d07d22020-04-27 18:20:16 +010071 new_op.inputs = [inp]
72 new_op.outputs = [tens]
73 new_op.attrs["concat_axis"] = axis
74 new_op.attrs["concat_start"] = offset
75 offset += inp.shape[axis]
76 new_op.attrs["concat_end"] = offset
77 new_op.run_on_npu = True
78 tens.ops.append(new_op)
79 assert tens.shape[axis] == offset
80
Patrik Gustavsson29d568e2020-08-18 10:11:21 +020081 # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a
82 # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte
83 # aligned. For other values of axis the address offsets will be 16 byte aligned, as they are all based on c = 0
Patrik Gustavsson458a2082020-08-13 13:41:05 +020084 # and those addresses are always 16 byte aligned due to the NHCWB16 format.
Patrik Gustavsson6c97e9a2020-09-23 11:02:18 +020085 if axis == -1 or axis == (len(tens.shape) - 1):
Patrik Gustavsson458a2082020-08-13 13:41:05 +020086 for op in tens.ops:
87 if op.attrs["concat_start"] % 16 != 0:
88 tens.avoid_NHCWB16 = True
89 break
90
Tim Hall79d07d22020-04-27 18:20:16 +010091 return tens
92
93
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +020094def rewrite_split(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +010095
Louis Verhaardaee5d752020-09-30 09:01:52 +020096 if len(tens.ops) == 1 and tens.ops[0].type.is_split_op():
Tim Hall79d07d22020-04-27 18:20:16 +010097 split_op = tens.ops[0]
98
99 # Not supported so leave it and run on CPU
100 if not split_op.run_on_npu:
101 return tens
102
103 inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis()
104
105 tens.ops = []
Louis Verhaardaee5d752020-09-30 09:01:52 +0200106 new_op = Operation(Op.SplitSliceRead, split_op.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100107 new_op.inputs = [inp]
Tim Hall79d07d22020-04-27 18:20:16 +0100108
109 # For Split the offset cannot be extracted from the tensor so it has to
110 # be calculated from the index of the output tensor
Diego Russoea6111a2020-04-14 18:41:58 +0100111 if axis is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100112 # Get the start and end of the split
113 offset_start = [0] * len(tens.shape)
114 offset_end = [0] * len(tens.shape)
115 for out in outputs:
116 if out == tens:
117 break
118 offset_start[axis] += out.shape[axis]
119
Patrik Gustavssoneebb1c22020-08-18 15:03:04 +0200120 # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input
121 if (offset_start[-1] % 16) != 0:
122 inp.avoid_NHCWB16 = True
123
Tim Hall79d07d22020-04-27 18:20:16 +0100124 offset_end[axis] = offset_start[axis] + tens.shape[axis]
125
126 new_op.attrs["split_start"] = offset_start
127 new_op.attrs["split_end"] = offset_end
128 new_op.run_on_npu = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100129 new_op.set_output_tensor(tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100130
131 return tens
132
133
134def needed_total_padding(input_size, stride, filter_size):
135 out_size = (input_size + stride - 1) // stride
136 needed_input = (out_size - 1) * stride + filter_size
137 total_padding = max(0, needed_input - input_size)
138 return total_padding
139
140
141def calc_padding_and_skirt(padding_type, kernel_size, stride, input_dims):
142 ypad = needed_total_padding(int(input_dims[1]), int(stride[1]), int(kernel_size[0]))
143 xpad = needed_total_padding(int(input_dims[2]), int(stride[2]), int(kernel_size[1]))
144 if padding_type == b"SAME":
145 left_pad = (xpad + 0) // 2
146 right_pad = (xpad + 1) // 2
147 top_pad = (ypad + 0) // 2
148 bottom_pad = (ypad + 1) // 2
149 elif padding_type == b"VALID":
150 left_pad = 0
151 right_pad = 0
152 top_pad = 0
153 bottom_pad = 0
154 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200155 raise UnsupportedFeatureError("Unknown padding {}".format(str(padding_type)))
Tim Hall79d07d22020-04-27 18:20:16 +0100156 padding = (top_pad, left_pad, bottom_pad, right_pad)
157 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
158 return padding, skirt
159
Tim Hallc30f4952020-06-15 20:47:35 +0100160
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200161def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_dims, upscaling_factor):
162 kernel_height, kernel_width = kernel_size[0], kernel_size[1]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200163 if padding_type == b"SAME":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200164 ypad = needed_total_padding(int(input_dims[1]) * upscaling_factor, int(stride[1]), int(kernel_height))
165 xpad = needed_total_padding(int(input_dims[2]) * upscaling_factor, int(stride[2]), int(kernel_width))
166
Jacob Bohlind47cc272020-08-24 11:42:14 +0200167 right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0)
168 bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200169 left_pad = max(kernel_width - 1 - right_pad, 0)
170 top_pad = max(kernel_height - 1 - bottom_pad, 0)
171
Jacob Bohlincf7da102020-05-20 09:03:40 +0200172 elif padding_type == b"VALID":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200173 right_pad = max(kernel_width - 2, 0)
174 bottom_pad = max(kernel_height - 2, 0)
175 left_pad = kernel_width - 1
176 top_pad = kernel_height - 1
Jacob Bohlincf7da102020-05-20 09:03:40 +0200177 else:
178 assert 0, "Unknown padding"
179
180 padding = (top_pad, left_pad, bottom_pad, right_pad)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200181 skirt = padding
Jacob Bohlincf7da102020-05-20 09:03:40 +0200182 return padding, skirt
183
Tim Hall79d07d22020-04-27 18:20:16 +0100184
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200185def fixup_conv2d_backprop(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200186 if op.type == Op.Conv2DBackpropInput:
Tim Hall79d07d22020-04-27 18:20:16 +0100187 # flip the inputs
188 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200189 op.type = Op.Conv2DBackpropInputSwitchedBias
Jacob Bohlincf7da102020-05-20 09:03:40 +0200190
191 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100192 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100193
194 return op
195
196
Charles Xu9a03fdf2020-07-02 15:12:40 +0200197# Convert the op to an elementwise add
198def convert_resizebilinear_1x1_to_add(op):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200199 op.type = Op.Add
Charles Xu9a03fdf2020-07-02 15:12:40 +0200200 op.name = op.name + "_add"
Charles Xu9a03fdf2020-07-02 15:12:40 +0200201 op.attrs["resizebilinear"] = True
202 # Create an input tensor filled with zeros
203 shape = op.outputs[0].shape
204 tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add")
205 tens.values = np.zeros(shape)
206 tens.quant_values = np.zeros(shape, np.uint8)
207 tens.quantization = QuantizationParameters(0.0, 255.0)
208 tens.quantization.scale_f32 = 1.0
209 tens.quantization.zero_point = 0
210 tens.consumer_list = [op]
211 tens_op = op.inputs[1].ops[0]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100212 tens_op.set_output_tensor(tens)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200213 # Set the add inputs
214 op.inputs[1] = op.inputs[0]
215 op.inputs[0] = tens
216
217 return op
218
219
Charles Xu87c13502020-08-06 12:17:26 +0200220# Convert ResizeBilinear to a number of 2x2 pool ops
221def convert_resizebilinear_to_2x2_pool(op):
222 count = 0
223 pre_op = op
224 outputs = op.outputs
225
226 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
227 if op.attrs["align_corners"]:
228 shape_modifier = 1
229 op.attrs["padding"] = b"VALID"
230 else:
231 shape_modifier = 0
232 op.attrs["padding"] = b"SAME"
233 op.inputs[0].resampling_mode = resampling_mode.NEAREST
234
235 upscaled_shape = np.array(op.inputs[0].shape[1:3])
236 out_shape = np.array(op.outputs[0].shape[1:3])
237 if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all():
238 return op
239
240 while (upscaled_shape < out_shape).all():
241 if count == 0:
242 scaled_op = pre_op
243 else:
244 scaled_op = op.clone("_{}".format(count))
245 scaled_op.inputs[0] = pre_op.outputs[0]
246
247 upscaled_shape = upscaled_shape * 2 - shape_modifier
248
249 if (upscaled_shape == out_shape).all():
250 scaled_op.outputs = outputs
251 scaled_op.outputs[0].ops = [scaled_op]
252 else:
253 shape = outputs[0].shape.copy()
254 shape[1:3] = upscaled_shape[0:2]
255 out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count))
256 out_tens.quantization = op.outputs[0].quantization.clone()
257 out_tens.quantization.quant_min = np.iinfo(np.int16).min
258 out_tens.quantization.quant_max = np.iinfo(np.int16).max
259 scaled_op.set_output_tensor(out_tens)
260 pre_op = scaled_op
261 count += 1
262
263 # Setup the scale value
264 if scaled_op.inputs[0].dtype.bits == 8 and scaled_op.outputs[0].dtype.bits == 16:
265 scaled_op.attrs["rescale"] = 128
266 elif scaled_op.inputs[0].dtype.bits == 16 and scaled_op.outputs[0].dtype.bits == 8:
267 scaled_op.attrs["rescale"] = 1 / 128
268 elif "rescale" in scaled_op.attrs:
269 del scaled_op.attrs["rescale"]
270
271 return op
272
273
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200274def fixup_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200275 if op.type == Op.ResizeBilinear and op.run_on_npu:
Charles Xu87c13502020-08-06 12:17:26 +0200276 if op.inputs[0].shape == op.outputs[0].shape:
Charles Xu36ffaf32020-08-05 15:40:44 +0200277 # Bypass nop resizebilinear
278 op.inputs = op.inputs[:1]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200279 op.type = Op.Identity
Charles Xu87c13502020-08-06 12:17:26 +0200280 elif op.inputs[0].shape[1] == 1 and op.inputs[0].shape[2] == 1:
281 convert_resizebilinear_1x1_to_add(op)
282 else:
283 convert_resizebilinear_to_2x2_pool(op)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200284
285 return op
286
287
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200288def convert_nop_split_to_identity(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200289 if op.type == Op.Split and op.attrs.get("num_splits") == 1:
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200290 # the list comprehension should return a list with a single tensor
291 # if it shouldn't, remove_passthrough_tensor will fail appropriately
292 op.inputs = [i for i in op.inputs if i.shape == op.outputs[0].shape]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200293 op.type = Op.Identity
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200294 return op
295
296
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200297def fixup_fully_connected_input(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200298 if op.type == Op.FullyConnected:
Tim Hall79d07d22020-04-27 18:20:16 +0100299 inp = op.inputs[0]
300 weights = op.inputs[1]
301
302 n_in_elems = weights.shape[-2]
303 elms = inp.elements()
304 batch_size = elms // n_in_elems
305 assert batch_size * n_in_elems == elms
306
307 desired_shape = [batch_size, n_in_elems]
308 if inp.shape != desired_shape:
309 # mismatch, insert a reshape to fix this.
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200310 op.set_input_tensor(create_reshape_tensor(inp, desired_shape), 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100311
312 return op
313
314
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200315def convert_batched_fc_to_conv(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200316 if op.type == Op.FullyConnected:
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200317 ifm = op.inputs[0]
318 ofm = op.outputs[0]
319 # Check if the FC is 2D and first dimension indicates batching
320 if len(ifm.shape) == len(ofm.shape) == 2 and ifm.shape[0] != 1:
321 n = ifm.shape[0]
322 batching_split = {4: (2, 2), 8: (2, 4), 16: (4, 4)}
323 h, w = batching_split.get(n, (1, n))
324
325 # Convert to convolution
326 op.name += "_conv"
Louis Verhaardaee5d752020-09-30 09:01:52 +0200327 op.type = Op.Conv2DBias
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200328 op.attrs = {
329 "dilation": (1, 1, 1, 1),
330 "dilation_h_factor": 1,
331 "dilation_w_factor": 1,
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200332 "padding": b"SAME",
333 "stride_h": 1,
334 "stride_w": 1,
335 "strides": (1, 1, 1, 1),
336 }
337
338 prev_op = ifm.ops[0]
339 desired_shape = [1, h, w, ifm.shape[-1]]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200340 if len(ifm.consumer_list) == 1 and prev_op is not None and prev_op.type == Op.Reshape:
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200341 # There is a preceding Reshape
342 # Compare input of prev_op and input of op, to see if prev_op can be removed
343 ifm_prev_op = prev_op.inputs[0]
344 if ifm_prev_op.shape == ifm.shape and ifm_prev_op.quantization.is_scaling_equal(ifm.quantization):
345 # prev_op can be removed
346 op.set_input_tensor(ifm_prev_op, 0)
347 else:
348 op.inputs[0].set_all_shapes(desired_shape)
349 prev_op.set_input_tensor(
350 create_const_tensor(prev_op.inputs[1].name, [1], DataType.int32, desired_shape), 1
351 )
352 prev_op.attrs["new_shape"] = desired_shape
353 else:
354 # Add reshape op to the input if there is no preceding reshape
355 ifm.consumer_list.remove(op)
356 op.set_input_tensor(create_reshape_tensor(ifm, desired_shape), 0)
357
358 # Reshape Weights to be 4D. IO becomes HWIO
359 weight_tensor = op.inputs[1]
360 weight_tensor.quant_values = np.expand_dims(np.expand_dims(weight_tensor.quant_values, axis=0), axis=0)
361 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
362
363 desired_shape = [1, h, w, ofm.shape[-1]]
364 if (
365 len(ofm.consumer_list) == 1
366 and ofm.consumer_list[0] is not None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200367 and ofm.consumer_list[0].type == Op.Reshape
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200368 ):
369 # There is a subsequent Reshape
370 # Compare desired shape and output of consumer op, to see if consumer op can be removed
371 ofm_cons_op = ofm.consumer_list[0].outputs[0]
372 if desired_shape == ofm_cons_op.shape and ofm.quantization.is_scaling_equal(ofm_cons_op.quantization):
373 op.outputs[0] = ofm_cons_op
374 op.outputs[0].ops = [op]
375 else:
376 op.outputs[0].set_all_shapes(desired_shape)
377 else:
378 # Add rehape op to the output
379 op.set_output_tensor(create_reshape_tensor(ofm, desired_shape, False))
380 return op
381
382
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200383def fixup_pack_input(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200384 if op.type == Op.Pack:
Tim Hall79d07d22020-04-27 18:20:16 +0100385 # Pack is also referred to as Stack
386 # Requires the rewrite_concat function to be called on the op afterwards
387 axis = int(op.attrs["axis"])
388 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
389
390 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100391 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100392
393 for idx, inp in enumerate(op.inputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100394 reshape_out = inp.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100395 reshape_out.set_all_shapes(desired_shape)
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100396
Louis Verhaardaee5d752020-09-30 09:01:52 +0200397 reshape_op = Operation(Op.Reshape, "{}{}_reshape".format(op.name, idx))
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100398 reshape_op.attrs["new_shape"] = desired_shape
399 reshape_op.inputs = [inp, new_shape_tens]
400 reshape_op.set_output_tensor(reshape_out)
Tim Hall79d07d22020-04-27 18:20:16 +0100401
402 op.inputs[idx] = reshape_out
403
Louis Verhaardaee5d752020-09-30 09:01:52 +0200404 op.type = Op.PackReshaped
Tim Hall79d07d22020-04-27 18:20:16 +0100405
406 return op
407
408
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200409def unfuse_activation_function(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200410 if op.type == Op.ConcatTFLite and op.run_on_npu and op.activation is not None:
411 act_op = Operation(op.activation, op.name + op.activation.name)
412 op.activation = None
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200413 out_tens = op.outputs[0]
414 intermediate_tens = out_tens.clone("_act_intermediate")
415 act_op.set_output_tensor(out_tens)
416 act_op.add_input_tensor(intermediate_tens)
417 op.set_output_tensor(intermediate_tens)
418
419 return op
420
Louis Verhaard8912c532020-09-30 12:11:49 +0200421
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200422def fixup_unpack_output(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100423 op = tens.ops[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200424 if op.type in set((Op.Unpack, Op.StridedSlice)):
Tim Hall79d07d22020-04-27 18:20:16 +0100425 # Unpack is also referred to as Unstack
426 # Requires the rewrite_split function to be called on the op afterwards
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200427
428 reshape_input_shape = tens.shape
Louis Verhaardaee5d752020-09-30 09:01:52 +0200429 if op.type == Op.StridedSlice:
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200430 new_axis_mask = op.attrs["new_axis_mask"]
Tim Hall79d07d22020-04-27 18:20:16 +0100431 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Louis Verhaard7db78962020-05-25 15:05:26 +0200432 ellipsis_mask = op.attrs["ellipsis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200433
434 if (new_axis_mask != 0 and shrink_axis_mask != 0) or ellipsis_mask != 0:
435 # Not supported, will be put on CPU
436 return tens
437 if shrink_axis_mask == 0 and new_axis_mask == 0:
Tim Hall79d07d22020-04-27 18:20:16 +0100438 # Equal Rank StridedSlice, no need to insert reshape
439 return tens
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200440 elif shrink_axis_mask != 0:
441 n = 0
442 axis = 0
443 while shrink_axis_mask:
444 prev_mask = shrink_axis_mask
445 n += 1
446 shrink_axis_mask &= shrink_axis_mask - 1
447 axis = int(math.log2(prev_mask - shrink_axis_mask))
448 reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100449
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200450 assert len(tens.shape) == (len(op.inputs[0].shape) - n)
451 op.attrs["shrink_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100452
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200453 elif new_axis_mask != 0:
454 n = 0
455 axis = 0
456 while new_axis_mask:
457 prev_mask = new_axis_mask
458 n += 1
459 new_axis_mask &= new_axis_mask - 1
460 axis = int(math.log2(prev_mask - new_axis_mask))
Louis Verhaard7db78962020-05-25 15:05:26 +0200461 reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1) :]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200462 new_axis_mask >>= 1
463
464 assert len(tens.shape) == (len(op.inputs[0].shape) + n)
465 op.attrs["new_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100466 else:
467 axis = int(op.attrs["axis"])
Louis Verhaardaee5d752020-09-30 09:01:52 +0200468 op.type = Op.UnpackReshaped
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200469 reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100470
471 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100472 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, tens.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100473
474 for idx, out_tens in enumerate(op.outputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100475 reshape_in = out_tens.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100476 reshape_in.set_all_shapes(reshape_input_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100477 reshape_in.ops = [op]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100478
Louis Verhaardaee5d752020-09-30 09:01:52 +0200479 reshape_op = Operation(Op.Reshape, "{}{}_reshape".format(op.name, idx))
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100480 reshape_op.attrs["new_shape"] = reshape_input_shape
Tim Hall79d07d22020-04-27 18:20:16 +0100481 reshape_op.inputs = [reshape_in, new_shape_tens]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100482 reshape_op.set_output_tensor(out_tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100483
484 op.outputs[idx] = reshape_in
485
486 return tens
487
488
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200489def add_padding_fields(op, arch, nng):
Jacob Bohlin90033f32020-08-28 15:45:44 +0200490 if op.run_on_npu:
491 if "padding" in op.attrs:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200492 if op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op():
Jacob Bohlin90033f32020-08-28 15:45:44 +0200493 kernel_size = op.inputs[1].shape[:2]
494 input_shape = op.inputs[0].shape
Louis Verhaardaee5d752020-09-30 09:01:52 +0200495 elif op.type.is_pool_op() or op.type.npu_block_type == NpuBlockType.ReduceSum:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200496 kernel_size = op.attrs["ksize"][1:3]
497 input_shape = op.inputs[0].shape
Jacob Bohlin90033f32020-08-28 15:45:44 +0200498 else:
499 raise UnsupportedFeatureError("Unknown operation that uses padding: {}".format(op.type))
Tim Hall79d07d22020-04-27 18:20:16 +0100500
Louis Verhaardaee5d752020-09-30 09:01:52 +0200501 if op.type == Op.Conv2DBackpropInputSwitchedBias:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200502 upscaling_factor = op.outputs[0].shape[1] // input_shape[1]
503 padding, skirt = calc_upscaled_padding_and_skirt(
504 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
505 )
506 else:
507 dilation_h, dilation_w = op.get_dilation_h_w()
508 dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1]
509 padding, skirt = calc_padding_and_skirt(
510 op.attrs["padding"], dilated_kernel_size, op.attrs["strides"], input_shape
511 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200512
Jacob Bohlin90033f32020-08-28 15:45:44 +0200513 op.attrs["explicit_padding"] = padding
514 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200515
Tim Hall79d07d22020-04-27 18:20:16 +0100516 return op
517
518
Tim Hall79d07d22020-04-27 18:20:16 +0100519# Check if the op can be reordered
520def get_prepend_op(op):
521 inp = op.inputs[0]
522 # The op should be reordered between prev_op and prep_op
523 prev_op = inp.ops[-1]
524 prep_op = None
525 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
526 prep_op = prev_op
527 inp = prev_op.inputs[0]
528 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100529 if prev_op is not None and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100530 return prep_op
531
532 return None
533
534
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200535def convert_depthwise_to_conv(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100536 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
537 # the ofm depth equals the depth multipler.
538 # If those conditions are true, then we can perform a simple
539 # switch of the operator type (and weight order)
540
Louis Verhaardaee5d752020-09-30 09:01:52 +0200541 if op.type == Op.DepthwiseConv2DBias and (op.attrs["depth_multiplier"] != 1):
Tim Hall79d07d22020-04-27 18:20:16 +0100542 ifm_tensor = op.inputs[0]
543 weight_tensor = op.inputs[1]
544 ofm_tensor = op.outputs[0]
545 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
546 # Change op type to Conv2d
Louis Verhaardaee5d752020-09-30 09:01:52 +0200547 op.type = Op.Conv2DBias
Tim Hall79d07d22020-04-27 18:20:16 +0100548 del op.attrs["channel_multiplier"]
549 del op.attrs["depth_multiplier"]
550
551 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100552 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100553 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200554 raise UnsupportedFeatureError(
555 "Unsupported DepthwiseConv2d with depth_multiplier = {}, ifm channels = {}, ofm channels = {}".format(
Tim Hall79d07d22020-04-27 18:20:16 +0100556 op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3]
557 )
558 )
Tim Hall79d07d22020-04-27 18:20:16 +0100559 return op
560
561
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200562def reorder_depthwise_weights(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200563 if op.type.is_depthwise_conv2d_op():
Jacob Bohline843d332020-06-23 12:12:56 +0200564 weight_tensor = op.inputs[1]
565 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100566 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200567 weight_tensor.weight_transpose_depthwise = True
568
569 return op
570
571
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200572def convert_conv_to_fc(op, arch, nng):
Michael McGeagh8d939c02020-07-29 13:11:43 +0100573 # Conv 1x1 can be equivalent to Fully Connected.
574 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
575 # caching/double buffering for the weights.
576 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200577 if op.type == Op.Conv2DBias:
Michael McGeagh8d939c02020-07-29 13:11:43 +0100578 _, h, w, _ = op.inputs[0].shape
579 kh, kw, _, _ = op.inputs[1].shape
580 if h == 1 and w == 1 and kh == 1 and kw == 1:
581 # Overwrite this op as a Fully Connected Op
582 op.name += "_fc"
Louis Verhaardaee5d752020-09-30 09:01:52 +0200583 op.type = Op.FullyConnected
Michael McGeagh8d939c02020-07-29 13:11:43 +0100584 op.attrs = {
Michael McGeagh8d939c02020-07-29 13:11:43 +0100585 "weights_format": 0,
Michael McGeagh8d939c02020-07-29 13:11:43 +0100586 }
587 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
588 weight_tensor = op.inputs[1]
589 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
590 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
591 # The output from a fully connected is expected to be 2D so we need to add a reshape layer to convert it
592 # back to 4D afterwards as the next layer is expecting that shape
593 orig_ofm_tensor = op.outputs[0]
594 # Reshape this ops output to be 2D: {(N*H*W), C} (We know N H and W are all 1 so this becomes {1, C})
595 fc_ofm_tensor = orig_ofm_tensor.clone("_fc")
596 fc_ofm_tensor.set_all_shapes([1, fc_ofm_tensor.shape[-1]])
597 fc_ofm_tensor.ops = [op]
598 # Add a reshape after the new OFM to convert it back to the original 4D shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100599 reshape_name = op.name + "_reshape"
600 new_shape_tens = create_const_tensor(reshape_name + "_shape", [1], DataType.int32, orig_ofm_tensor.shape)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200601 reshape_op = Operation(Op.Reshape, reshape_name)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100602 reshape_op.attrs["new_shape"] = orig_ofm_tensor.shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100603 reshape_op.inputs = [fc_ofm_tensor, new_shape_tens]
604 reshape_op.set_output_tensor(orig_ofm_tensor)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100605 # Replace this ops OFM to point to the 2D tensor
606 op.outputs[0] = fc_ofm_tensor
607 return op
608
609
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200610def fixup_relus_with_differing_ifm_ofm_scaling(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200611 if op.run_on_npu and op.type.is_relu_op():
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100612 ifm = op.inputs[0]
613 ofm = op.outputs[0]
614 # Relu with differing IFM and OFM scaling cannot be fused with another primary op
615 # and requires its own to be inserted
616 if not ifm.is_scaling_equal(ofm):
617 # Override this op with its own primary op (avgpool)
618 relu_fused_op = create_avgpool_nop(op.name + "_avgpool")
619 # And fuse the original activation function to it
Louis Verhaardaee5d752020-09-30 09:01:52 +0200620 relu_fused_op.activation = op.type
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100621 # Tidy up and assign the ifm and ofm to the new op
622 ifm.consumer_list.remove(op)
Andreas Nevalainenf3d737e2020-09-25 14:12:43 +0200623
624 # if not 4d, reshape ifm/ofm
625 if len(ifm.shape) < 4:
626 ifm_shaped = create_reshape_tensor(ifm, full_shape(4, ifm.shape, 1))
627 ifm = ifm_shaped
628 if len(ofm.shape) < 4:
629 ofm_shaped = create_reshape_tensor(ofm, full_shape(4, ofm.shape, 1), False)
630 ofm = ofm_shaped
631
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100632 relu_fused_op.add_input_tensor(ifm)
633 relu_fused_op.set_output_tensor(ofm)
634 op = relu_fused_op
635 return op
636
637
Tim Hall79d07d22020-04-27 18:20:16 +0100638# Reorder activation op if it's after the memory only operations
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200639def fixup_act_reorder(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200640 if op.type.is_relu_op() or op in set((Op.Sigmoid, Op.Tanh)):
Tim Hall79d07d22020-04-27 18:20:16 +0100641 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100642 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100643 act_op = op.clone("_reordered")
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200644
645 # There is only one input tensor, overwrite it
646 act_op.set_input_tensor(prep_op.inputs[0], 0)
647
Tim Hall79d07d22020-04-27 18:20:16 +0100648 act_op_out = act_op.inputs[0].clone("_acted")
649 act_op_out.quantization = op.outputs[0].quantization.clone()
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100650 act_op.set_output_tensor(act_op_out)
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200651
652 # Update the consumer list
653 act_op_out.consumer_list = op.outputs[0].consumer_list.copy()
654 act_op_out.consumer_list.append(prep_op)
655
Tim Hall79d07d22020-04-27 18:20:16 +0100656 prep_op.inputs[0] = act_op_out
657 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
658
659 # Mark the op so that it will be removed as passthrough later on
Louis Verhaardaee5d752020-09-30 09:01:52 +0200660 op.type = Op.Identity
Tim Hall79d07d22020-04-27 18:20:16 +0100661 return op
662
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200663
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200664def fixup_elementwise_with_scalars(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200665 if op.type.is_binary_elementwise_op():
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200666 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200667 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
668 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
669 if diff > 0:
670 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
671 elif diff < 0:
672 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200673 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
674 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
675 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
676 ifm_tensor.storage_shape = ifm_tensor.shape
677 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
678 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
679 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
680 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200681 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100682
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200683
Tim Hall4e127762020-05-15 16:05:49 +0100684# Set input/output tensor equivalence to the same id for memory operations
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200685def set_tensor_equivalence(op, arch, nng):
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100686 if op.type in memory_only_ops:
Tim Hall4e127762020-05-15 16:05:49 +0100687 eid = op.outputs[0].equivalence_id
688 for inp in op.inputs:
689 inp.equivalence_id = eid
690 return op
691
692
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200693def convert_softmax(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200694 if op.type == Op.Softmax and op.run_on_npu:
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200695 softmax = SoftMax(op)
696 op = softmax.get_graph()
697 return op
698
699
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200700def convert_mul_max_to_abs_or_lrelu(op, arch, nng):
Diego Russoea6111a2020-04-14 18:41:58 +0100701 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100702
703 Input X For X = -1 or X > 0
704 | \ / This subgraph can be replaced with either
705 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
706 | /
707 Max
708 """
709
Louis Verhaardaee5d752020-09-30 09:01:52 +0200710 if op.type == Op.Maximum:
Tim Hall79d07d22020-04-27 18:20:16 +0100711 # finds the Mul input(s) to the Max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200712 muls = [i for i in op.inputs if i.ops[0].type == Op.Mul]
Tim Hall79d07d22020-04-27 18:20:16 +0100713 if len(muls) == 1:
714 mul = muls[0].ops[0]
715 elif len(muls) == 2:
716 # In the case both inputs are Muls, find the one with the same input as the Max
717 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
718 else:
719 # No Mul inputs
720 return op
721
722 # make sure the Mul doesn't have any other consumers
Louis Verhaardd7911c42020-08-25 13:36:41 +0200723 mul_ofm = mul.outputs[0]
724 if len(mul_ofm.consumers()) != 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100725 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200726 # make sure the Mul doesn't have a fused activation function
727 if mul.activation:
Tim Hall79d07d22020-04-27 18:20:16 +0100728 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200729 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200730 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
731 return op
Louis Verhaardd7911c42020-08-25 13:36:41 +0200732 if not ifm.is_scaling_equal(ofm) or not ifm.is_scaling_equal(mul_ofm):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200733 # rewrite to LeakyRelu currently only makes sense if the quantization is identical
734 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100735
736 # finds the branched input that goes to both the Max and the Mul
737 shared = set(op.inputs) & set(mul.inputs)
738 if len(shared) == 1:
739 shared_in = shared.pop()
740 # find the constant scalar input to the Mul
741 const_tens = (set(mul.inputs) - {shared_in}).pop()
742 # check that it is a scalar
743 if const_tens.shape != []:
744 return op
745 const = const_tens.ops[0]
746 # check that it is a constant
Louis Verhaardaee5d752020-09-30 09:01:52 +0200747 if const.type != Op.Const:
Tim Hall79d07d22020-04-27 18:20:16 +0100748 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200749 # Remove the Mul from the shared input's consumers
750 shared_in.consumer_list.remove(mul)
Tim Hall79d07d22020-04-27 18:20:16 +0100751 else:
752 return op
753
754 val = const.outputs[0].values
755 if val >= 0:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200756 new_op = Op.LeakyRelu
Tim Hall79d07d22020-04-27 18:20:16 +0100757 op.attrs["alpha"] = val
Louis Verhaardd7911c42020-08-25 13:36:41 +0200758 # to produce bit exact results, the alpha is not enough;
759 # save additional scaling info in attr "alpha_scale", to be used as input
760 # to the LUT construction
761 alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point
762 mul_ifm_scale = np.double(ifm.quantization.scale_f32)
763 mul_ifm2_scale = np.double(const_tens.quantization.scale_f32)
764 mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32)
765 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale)
766 op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift)
Tim Hall79d07d22020-04-27 18:20:16 +0100767 elif val == -1:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200768 new_op = Op.Abs
Tim Hall79d07d22020-04-27 18:20:16 +0100769 else:
770 return op
771
Louis Verhaardaee5d752020-09-30 09:01:52 +0200772 op.type = new_op
773 op.name = op.name.replace("Maximum", new_op.name)
774 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100775 op.inputs = [shared_in]
776 return op
777
778
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200779def convert_lrelu_to_mul_max(op, arch):
780 # Converts LeakyRelu to Max(alpha * IFM, identity * IFM)
781 # (the opposite of convert_mul_max_to_abs_or_lrelu)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200782 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200783
784 # Add multiplication with alpha
Louis Verhaardaee5d752020-09-30 09:01:52 +0200785 mul_alpha = Operation(Op.Mul, op.name + "_mul_alpha")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200786 mul_alpha.add_input_tensor(ifm)
787 # Create const tensor containing alpha as scalar
788 alpha = op.attrs["alpha"]
789 quantization = ifm.quantization.clone()
790 quantization.min = 0
791 quantization.max = alpha * (quantization.quant_max - quantization.quant_min)
792 quantization.scale_f32 = alpha
793 quantization.zero_point = 0
794 alpha_tens = create_const_tensor(op.name + "_alpha_scalar", [], ifm.dtype, [1], np.int8, quantization=quantization)
795 mul_alpha.add_input_tensor(alpha_tens)
796 fm_alpha = ofm.clone(op.name + "_alpha")
797 mul_alpha.set_output_tensor(fm_alpha)
798
799 if ifm.is_scaling_equal(ofm):
800 # No identity multiplication is needed
801 fm_id = ifm
802 else:
803 # Add multiplication with identity
Louis Verhaardaee5d752020-09-30 09:01:52 +0200804 mul_identity = Operation(Op.Mul, op.name + "_mul_identity")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200805 mul_identity.add_input_tensor(ifm)
806 # Create const tensor containing identity as scalar
807 quantization = ifm.quantization.clone()
808 quantization.min = 0
809 quantization.max = quantization.quant_max - quantization.quant_min
810 quantization.scale_f32 = 1
811 quantization.zero_point = 0
812 identity_tens = create_const_tensor(
813 op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization
814 )
815 mul_identity.add_input_tensor(identity_tens)
816 fm_id = ofm.clone(op.name + "_id")
817 mul_identity.set_output_tensor(fm_id)
818
819 # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs
Louis Verhaardaee5d752020-09-30 09:01:52 +0200820 op.type = Op.Maximum
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200821 op.name = op.name.replace("LeakyRelu", "Maximum")
822 op.inputs = []
823 ifm.consumer_list.remove(op)
824 op.add_input_tensor(fm_alpha)
825 op.add_input_tensor(fm_id)
826 return op
827
828
Louis Verhaardf03bad32020-09-25 08:30:44 +0200829def convert_to_lut(op, lut_values):
830 # Rewrite the operation by Add with scalar 0 + LUT activation
831 ifm = op.inputs[0]
Louis Verhaard58520b92020-08-24 16:45:38 +0200832 assert ifm.dtype.size_in_bytes() == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +0200833 op.type = Op.Add
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200834 op.name = op.name + "_add"
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200835 # Mark as no-op to enable potential fusing optimizations
836 op.attrs["is_nop"] = True
837 # Create an input tensor containing scalar zero
838 quantization = QuantizationParameters(0.0, 255.0)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200839 quantization.scale_f32 = ifm.quantization.scale_f32
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200840 quantization.zero_point = 0
841 tens = create_const_tensor(op.inputs[0].name + "_add", [], ifm.dtype, [0], np.uint8, quantization=quantization)
842 op.add_input_tensor(tens)
Louis Verhaardf03bad32020-09-25 08:30:44 +0200843 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
844 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
845 # should be the same as the IFM
Louis Verhaardaee5d752020-09-30 09:01:52 +0200846 op.forced_output_quantization = ifm.quantization
Louis Verhaardf03bad32020-09-25 08:30:44 +0200847 lut_tensor = lut.create_lut_tensor(op.name + "_lut", lut_values, DataType.int8)
848 op.set_activation_lut(lut_tensor)
849 return op
850
851
852def convert_to_lut8(op, fn):
853 # Converts op to a no-op + int8/uint8 LUT which is generated with the given function.
854 # fn is a function(real) -> real
Louis Verhaardaee5d752020-09-30 09:01:52 +0200855 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardf03bad32020-09-25 08:30:44 +0200856 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
857 return op
858 # Generate the LUT
859 ifm_scale = np.double(ifm.quantization.scale_f32)
860 ofm_scale = np.double(ofm.quantization.scale_f32)
861 zp_in = ifm.quantization.zero_point
862 zp_out = ofm.quantization.zero_point
863 values = []
864 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
865 quantized_min = min(ix)
866 quantized_max = max(ix)
867 for x in ix:
868 x_real = ifm_scale * (x - zp_in)
869 y_real = fn(x_real)
870 lut_result = round_away_zero(zp_out + y_real / ofm_scale)
871 lut_result = min(quantized_max, max(quantized_min, lut_result))
872 values.append(lut_result)
873 return convert_to_lut(op, values)
874
875
876def convert_lrelu_to_lut(op, arch):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200877 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200878 # Generate the LUT
Louis Verhaardd7911c42020-08-25 13:36:41 +0200879 alpha = op.attrs["alpha"]
880 ifm_scale = np.double(ifm.quantization.scale_f32)
881 ofm_scale = np.double(ofm.quantization.scale_f32)
882 zp_in = ifm.quantization.zero_point
883 zp_out = ofm.quantization.zero_point
884 identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale)
885 alpha_scalar = 1
886 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale)
887 if "alpha_scaling" in op.attrs:
888 # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu
889 alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"]
890 values = []
Louis Verhaard58520b92020-08-24 16:45:38 +0200891 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200892 quantized_min = min(ix)
893 quantized_max = max(ix)
894 for x in ix:
895 if x < zp_in:
896 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(
897 alpha_scalar * (x - zp_in), alpha_scale, alpha_shift
898 )
899 else:
900 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift)
901 lut_result = min(quantized_max, max(quantized_min, lut_result))
902 values.append(lut_result)
Louis Verhaardf03bad32020-09-25 08:30:44 +0200903 return convert_to_lut(op, values)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200904
905
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200906def convert_lrelu(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200907 # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200908 if op.type != Op.LeakyRelu:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200909 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200910 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardd7911c42020-08-25 13:36:41 +0200911 if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype:
912 # use LUT for int8/uint8
913 return convert_lrelu_to_lut(op, arch)
914 if ifm.is_scaling_equal(ofm) and ifm.dtype == ofm.dtype and ifm.dtype == DataType.int16:
915 # use LeakyRelu unmodified for int16 with equal input/output scaling
916 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200917 return convert_lrelu_to_mul_max(op, arch)
918
919
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200920def convert_tanh_sigmoid_to_lut(op, arch, nng):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200921 # Converts int8/uint8 Sigmoid and Tanh to a LUT based solution
Louis Verhaardaee5d752020-09-30 09:01:52 +0200922 if op.type == Op.Sigmoid:
Louis Verhaard8912c532020-09-30 12:11:49 +0200923 return convert_to_lut8(op, clamp_sigmoid)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200924 elif op.type == Op.Tanh:
Louis Verhaardf03bad32020-09-25 08:30:44 +0200925 return convert_to_lut8(op, math.tanh)
926 return op
927
928
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200929def remove_unwanted_reshapes(op, arch, nng):
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200930 # Try to remove reshapes enclosing ElementWise operator with only one non-constant input
Louis Verhaardaee5d752020-09-30 09:01:52 +0200931 if not op.run_on_npu or not op.type.is_elementwise_op():
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200932 return op
933
934 # Check if the ElementWise operator only have one non-constant input
Louis Verhaardaee5d752020-09-30 09:01:52 +0200935 non_const_tens = [x for x in op.inputs if x.ops[0].type != Op.Const]
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200936 if len(non_const_tens) != 1:
937 return op
938 ifm = non_const_tens[0]
939
940 # Check if operation is enclosed by Reshapes that can be removed
941 ofm = op.outputs[0]
942 prev_op = ifm.ops[0]
943 if (
944 len(ifm.consumer_list) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +0200945 and prev_op.type == Op.Reshape
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200946 and len(ofm.consumer_list) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +0200947 and ofm.consumer_list[0].type == Op.Reshape
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200948 ):
949 # Operation is enclosed by reshapes, check if they can be removed
Louis Verhaardaee5d752020-09-30 09:01:52 +0200950 prev_op_ifm, prev_op_ofm = prev_op.get_ifm_ofm()
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200951 cons_op = ofm.consumer_list[0]
952 cons_op_ifm = ofm
953 cons_op_ofm = cons_op.outputs[0]
954 if len(prev_op_ifm.shape) == len(cons_op_ofm.shape):
955 # Check if quantization is the same in the input and output for the reshape ops
956 if prev_op_ifm.quantization.is_scaling_equal(
957 prev_op_ofm.quantization
958 ) and cons_op_ifm.quantization.is_scaling_equal(cons_op_ofm.quantization):
Patrik Gustavsson7ad862a2020-09-29 14:09:43 +0200959 op.set_input_tensor(prev_op_ifm, 0)
960 op.set_output_tensor(cons_op_ofm)
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200961 return op
962
963
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200964def fuse_activation_function_with_prev(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200965 # if op is a no-op: attempts to move the activation function to the preceding op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200966 if not op.attrs.get("is_nop", False) or op.activation is None:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200967 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200968 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200969 # finds the input(s) to the operation
970 prev_op = ifm.ops[0]
971 # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed
972 fuse = (
973 prev_op.run_on_npu
Louis Verhaardaee5d752020-09-30 09:01:52 +0200974 and prev_op.type.npu_block_type != NpuBlockType.Default
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200975 and len(ifm.ops) == 1
976 and len(prev_op.outputs[0].consumers()) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +0200977 and prev_op.activation is None
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200978 )
979 if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0:
980 # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC),
981 # LUT currently only works correctly for elementwise ops
982 fuse = False
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200983 if not fuse:
984 return op
985 # Move the fused activation function + corresponding info to prev_op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200986 prev_op.activation = op.activation
987 prev_op.forced_output_quantization = op.forced_output_quantization
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200988 if op.activation_lut is not None:
989 prev_op.set_activation_lut(op.activation_lut)
990 # Bypass op
Louis Verhaard98a34992020-09-01 10:39:04 +0200991 prev_op.set_output_tensor(ofm)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200992 return op
993
994
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200995def add_attrs_to_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200996 if op.type == Op.ResizeBilinear and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +0200997 input_tensor = op.inputs[0]
998 upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2]
999 out_shape = op.outputs[0].shape[1:3]
1000 if not op.attrs["align_corners"] and out_shape == upscaled_shape:
1001 # this means the output is supposed to be a x2 upscale,
1002 # so we need to do SAME padding
1003 op.attrs["padding"] = b"SAME"
1004 elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]:
1005 # here we can just run the avg pool without padding and
1006 # produce a (M * 2 - 1, N * 2 - 1) sized output
1007 op.attrs["padding"] = b"VALID"
1008 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +02001009 return op
Dwight Lidman42fed942020-05-29 09:37:03 +02001010 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +01001011 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +02001012 return op
1013
1014
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001015def fixup_bias_tensors(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001016 if op.type.needs_bias() and op.bias is None:
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001017 # Op has no bias, add bias tensor filled with zeros
1018 nr_biases = op.inputs[1].shape[-1]
1019 bias_values = [0] * nr_biases
1020 bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values)
1021 bias_tensor.quant_values = bias_tensor.values
1022 op.set_input_tensor(bias_tensor, -1)
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +02001023
1024 return op
1025
1026
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001027def supported_operator_check(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +01001028 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
1029 return op
1030
1031
1032def optimise_graph_a(nng, arch, verbose_graph=False):
1033 if verbose_graph:
1034 nng.print_graph()
1035
1036 op_rewrite_list = [
Tim Hall4e127762020-05-15 16:05:49 +01001037 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +01001038 supported_operator_check,
1039 # then do any rewrites of supported operators
1040 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +01001041 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +02001042 convert_softmax,
Tim Hall79d07d22020-04-27 18:20:16 +01001043 fixup_fully_connected_input,
Patrik Gustavssoncb337042020-09-16 14:55:40 +02001044 convert_batched_fc_to_conv,
Tim Hall79d07d22020-04-27 18:20:16 +01001045 fixup_pack_input,
Fredrik Svedberg0f98b362020-09-29 10:00:39 +02001046 unfuse_activation_function,
Tim Hall79d07d22020-04-27 18:20:16 +01001047 fixup_conv2d_backprop,
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +01001048 fixup_relus_with_differing_ifm_ofm_scaling,
Tim Hall79d07d22020-04-27 18:20:16 +01001049 fixup_act_reorder,
Charles Xu78792222020-05-13 10:15:26 +02001050 fixup_elementwise_with_scalars,
Jacob Bohline843d332020-06-23 12:12:56 +02001051 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +02001052 fixup_resizebilinear,
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001053 fixup_bias_tensors,
Dwight Lidmanc3862c22020-09-14 15:22:33 +02001054 convert_nop_split_to_identity,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001055 convert_mul_max_to_abs_or_lrelu,
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001056 remove_unwanted_reshapes,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001057 convert_lrelu,
Louis Verhaardf03bad32020-09-25 08:30:44 +02001058 convert_tanh_sigmoid_to_lut,
Tim Hall79d07d22020-04-27 18:20:16 +01001059 ]
1060
1061 for idx, sg in enumerate(nng.subgraphs):
1062 # rewrite graph pass
1063 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001064 nng, sg, arch, [fixup_unpack_output], op_rewrite_list, rewrite_unsupported=False
Tim Hall79d07d22020-04-27 18:20:16 +01001065 )
1066
1067 for idx, sg in enumerate(nng.subgraphs):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001068 # remove passthrough tensors and attempt further optimizations
1069 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001070 nng, sg, arch, [remove_passthrough_tensor], [fuse_activation_function_with_prev, add_padding_fields]
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001071 )
Tim Hall79d07d22020-04-27 18:20:16 +01001072
1073 if verbose_graph:
1074 nng.print_graph()
1075 return nng
1076
Diego Russoea6111a2020-04-14 18:41:58 +01001077
Tim Hall79d07d22020-04-27 18:20:16 +01001078def optimise_graph_b(nng, arch, verbose_graph=False):
1079 if verbose_graph:
1080 nng.print_graph()
1081
1082 for idx, sg in enumerate(nng.subgraphs):
1083 # combined rewrite graph pass
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001084 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(nng, sg, arch, [rewrite_concat, rewrite_split], [])
Tim Hall79d07d22020-04-27 18:20:16 +01001085
1086 if verbose_graph:
1087 nng.print_graph()
1088 return nng