blob: 4f435dcb29a891aa24d6c3d3a19a04166b4b4675 [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
35from .operation import Operation
Fredrik Svedberga0c36242020-06-03 15:43:31 +020036from .softmax import SoftMax
Michael McGeaghc5b549b2020-08-07 11:54:28 +010037from .tensor import create_const_tensor
38from .tensor import create_reshape_tensor
Charles Xu9a03fdf2020-07-02 15:12:40 +020039from .tensor import QuantizationParameters
Diego Russoe8a10452020-04-21 17:39:10 +010040from .tensor import Tensor
Tim Hall79d07d22020-04-27 18:20:16 +010041
42passthrough_nodes = set(("Identity",))
43
Michael McGeagh11b0bdb2020-09-08 11:07:35 +010044conv_op = set(("Conv2D", "QuantizedConv2D", "Conv2DBackpropInputSwitchedBias", "Conv2DBiasAct"))
45fc_op = set(
46 (
47 "MatMul",
48 "QuantizedMatMul",
49 "BlockLSTM",
50 "RnnAct",
51 "UnidirectionalSequenceRnnAct",
52 "BidirectionalSequenceRnnAct",
53 "LstmAct",
54 "UnidirectionalSequenceLstmAct",
55 "BidirectionalSequenceLstmAct",
56 "FullyConnectedAct",
57 )
58)
59depthwise_op = set(("DepthwiseConv2dNative", "DepthwiseConv2dBiasAct",))
60pool_op = set(
61 ("AvgPool", "MaxPool", "QuantizedAvgPool", "QuantizedMaxPool", "AvgPoolAct", "MaxPoolAct", "ResizeBilinear")
62)
63reduce_sum_ops = set(("ReduceSum",))
64binary_elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum"))
65elementwise_op = set(("LeakyRelu", "Abs", "CLZ", "SHL", "SHR")) | binary_elementwise_op
66relu_ops = set(("Relu", "Relu6", "ReluN1To1"))
67activation_ops = set(("Sigmoid", "Tanh")) | relu_ops
68memory_only_ops = set(("Reshape",))
69
Tim Hall79d07d22020-04-27 18:20:16 +010070
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +020071def remove_passthrough_tensor(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +010072 if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes:
73 assert len(tens.ops[0].inputs) == 1
74 tens = tens.ops[0].inputs[0]
75 return tens
76
77
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +020078def rewrite_concat(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +010079 if len(tens.ops) == 1 and tens.ops[0].is_concat_op():
80 concat_op = tens.ops[0]
81 if tens != concat_op.outputs[0]:
82 return tens # don't attempt to rewrite the min/max outputs of QuantizedConcat
83
84 # Not supported so leave it and run on CPU
85 if not concat_op.run_on_npu:
86 return tens
87
88 inputs, axis = concat_op.get_concat_inputs_axis()
89
90 tens.ops = []
91 offset = 0
92 for idx, inp in enumerate(inputs):
93 new_op = Operation("ConcatSliceWrite", concat_op.name + str(idx))
94 new_op.inputs = [inp]
95 new_op.outputs = [tens]
96 new_op.attrs["concat_axis"] = axis
97 new_op.attrs["concat_start"] = offset
98 offset += inp.shape[axis]
99 new_op.attrs["concat_end"] = offset
100 new_op.run_on_npu = True
101 tens.ops.append(new_op)
102 assert tens.shape[axis] == offset
103
Patrik Gustavsson29d568e2020-08-18 10:11:21 +0200104 # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a
105 # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte
106 # 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 +0200107 # and those addresses are always 16 byte aligned due to the NHCWB16 format.
Patrik Gustavsson6c97e9a2020-09-23 11:02:18 +0200108 if axis == -1 or axis == (len(tens.shape) - 1):
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200109 for op in tens.ops:
110 if op.attrs["concat_start"] % 16 != 0:
111 tens.avoid_NHCWB16 = True
112 break
113
Tim Hall79d07d22020-04-27 18:20:16 +0100114 return tens
115
116
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200117def rewrite_split(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100118
119 if len(tens.ops) == 1 and tens.ops[0].is_split_op():
120 split_op = tens.ops[0]
121
122 # Not supported so leave it and run on CPU
123 if not split_op.run_on_npu:
124 return tens
125
126 inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis()
127
128 tens.ops = []
129 new_op = Operation("SplitSliceRead", split_op.name)
130 new_op.inputs = [inp]
Tim Hall79d07d22020-04-27 18:20:16 +0100131
132 # For Split the offset cannot be extracted from the tensor so it has to
133 # be calculated from the index of the output tensor
Diego Russoea6111a2020-04-14 18:41:58 +0100134 if axis is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100135 # Get the start and end of the split
136 offset_start = [0] * len(tens.shape)
137 offset_end = [0] * len(tens.shape)
138 for out in outputs:
139 if out == tens:
140 break
141 offset_start[axis] += out.shape[axis]
142
Patrik Gustavssoneebb1c22020-08-18 15:03:04 +0200143 # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input
144 if (offset_start[-1] % 16) != 0:
145 inp.avoid_NHCWB16 = True
146
Tim Hall79d07d22020-04-27 18:20:16 +0100147 offset_end[axis] = offset_start[axis] + tens.shape[axis]
148
149 new_op.attrs["split_start"] = offset_start
150 new_op.attrs["split_end"] = offset_end
151 new_op.run_on_npu = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100152 new_op.set_output_tensor(tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100153
154 return tens
155
156
157def needed_total_padding(input_size, stride, filter_size):
158 out_size = (input_size + stride - 1) // stride
159 needed_input = (out_size - 1) * stride + filter_size
160 total_padding = max(0, needed_input - input_size)
161 return total_padding
162
163
164def calc_padding_and_skirt(padding_type, kernel_size, stride, input_dims):
165 ypad = needed_total_padding(int(input_dims[1]), int(stride[1]), int(kernel_size[0]))
166 xpad = needed_total_padding(int(input_dims[2]), int(stride[2]), int(kernel_size[1]))
167 if padding_type == b"SAME":
168 left_pad = (xpad + 0) // 2
169 right_pad = (xpad + 1) // 2
170 top_pad = (ypad + 0) // 2
171 bottom_pad = (ypad + 1) // 2
172 elif padding_type == b"VALID":
173 left_pad = 0
174 right_pad = 0
175 top_pad = 0
176 bottom_pad = 0
177 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200178 raise UnsupportedFeatureError("Unknown padding {}".format(str(padding_type)))
Tim Hall79d07d22020-04-27 18:20:16 +0100179 padding = (top_pad, left_pad, bottom_pad, right_pad)
180 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
181 return padding, skirt
182
Tim Hallc30f4952020-06-15 20:47:35 +0100183
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200184def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_dims, upscaling_factor):
185 kernel_height, kernel_width = kernel_size[0], kernel_size[1]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200186 if padding_type == b"SAME":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200187 ypad = needed_total_padding(int(input_dims[1]) * upscaling_factor, int(stride[1]), int(kernel_height))
188 xpad = needed_total_padding(int(input_dims[2]) * upscaling_factor, int(stride[2]), int(kernel_width))
189
Jacob Bohlind47cc272020-08-24 11:42:14 +0200190 right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0)
191 bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200192 left_pad = max(kernel_width - 1 - right_pad, 0)
193 top_pad = max(kernel_height - 1 - bottom_pad, 0)
194
Jacob Bohlincf7da102020-05-20 09:03:40 +0200195 elif padding_type == b"VALID":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200196 right_pad = max(kernel_width - 2, 0)
197 bottom_pad = max(kernel_height - 2, 0)
198 left_pad = kernel_width - 1
199 top_pad = kernel_height - 1
Jacob Bohlincf7da102020-05-20 09:03:40 +0200200 else:
201 assert 0, "Unknown padding"
202
203 padding = (top_pad, left_pad, bottom_pad, right_pad)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200204 skirt = padding
Jacob Bohlincf7da102020-05-20 09:03:40 +0200205 return padding, skirt
206
Tim Hall79d07d22020-04-27 18:20:16 +0100207
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200208def fixup_conv2d_backprop(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100209 if op.type == "Conv2DBackpropInput":
210 # flip the inputs
211 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200212 op.type = "Conv2DBackpropInputSwitchedBias"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200213
214 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100215 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100216
217 return op
218
219
Charles Xu9a03fdf2020-07-02 15:12:40 +0200220# Convert the op to an elementwise add
221def convert_resizebilinear_1x1_to_add(op):
222 op.type = "AddAct"
223 op.name = op.name + "_add"
224 op.attrs.update({"npu_block_type": NpuBlockType.ElementWise})
225 op.attrs["resizebilinear"] = True
226 # Create an input tensor filled with zeros
227 shape = op.outputs[0].shape
228 tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add")
229 tens.values = np.zeros(shape)
230 tens.quant_values = np.zeros(shape, np.uint8)
231 tens.quantization = QuantizationParameters(0.0, 255.0)
232 tens.quantization.scale_f32 = 1.0
233 tens.quantization.zero_point = 0
234 tens.consumer_list = [op]
235 tens_op = op.inputs[1].ops[0]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100236 tens_op.set_output_tensor(tens)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200237 # Set the add inputs
238 op.inputs[1] = op.inputs[0]
239 op.inputs[0] = tens
240
241 return op
242
243
Charles Xu87c13502020-08-06 12:17:26 +0200244# Convert ResizeBilinear to a number of 2x2 pool ops
245def convert_resizebilinear_to_2x2_pool(op):
246 count = 0
247 pre_op = op
248 outputs = op.outputs
249
250 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
251 if op.attrs["align_corners"]:
252 shape_modifier = 1
253 op.attrs["padding"] = b"VALID"
254 else:
255 shape_modifier = 0
256 op.attrs["padding"] = b"SAME"
257 op.inputs[0].resampling_mode = resampling_mode.NEAREST
258
259 upscaled_shape = np.array(op.inputs[0].shape[1:3])
260 out_shape = np.array(op.outputs[0].shape[1:3])
261 if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all():
262 return op
263
264 while (upscaled_shape < out_shape).all():
265 if count == 0:
266 scaled_op = pre_op
267 else:
268 scaled_op = op.clone("_{}".format(count))
269 scaled_op.inputs[0] = pre_op.outputs[0]
270
271 upscaled_shape = upscaled_shape * 2 - shape_modifier
272
273 if (upscaled_shape == out_shape).all():
274 scaled_op.outputs = outputs
275 scaled_op.outputs[0].ops = [scaled_op]
276 else:
277 shape = outputs[0].shape.copy()
278 shape[1:3] = upscaled_shape[0:2]
279 out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count))
280 out_tens.quantization = op.outputs[0].quantization.clone()
281 out_tens.quantization.quant_min = np.iinfo(np.int16).min
282 out_tens.quantization.quant_max = np.iinfo(np.int16).max
283 scaled_op.set_output_tensor(out_tens)
284 pre_op = scaled_op
285 count += 1
286
287 # Setup the scale value
288 if scaled_op.inputs[0].dtype.bits == 8 and scaled_op.outputs[0].dtype.bits == 16:
289 scaled_op.attrs["rescale"] = 128
290 elif scaled_op.inputs[0].dtype.bits == 16 and scaled_op.outputs[0].dtype.bits == 8:
291 scaled_op.attrs["rescale"] = 1 / 128
292 elif "rescale" in scaled_op.attrs:
293 del scaled_op.attrs["rescale"]
294
295 return op
296
297
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200298def fixup_resizebilinear(op, arch, nng):
Charles Xu87c13502020-08-06 12:17:26 +0200299 if op.type == "ResizeBilinear" and op.run_on_npu:
300 if op.inputs[0].shape == op.outputs[0].shape:
Charles Xu36ffaf32020-08-05 15:40:44 +0200301 # Bypass nop resizebilinear
302 op.inputs = op.inputs[:1]
303 op.type = "Identity"
Charles Xu87c13502020-08-06 12:17:26 +0200304 elif op.inputs[0].shape[1] == 1 and op.inputs[0].shape[2] == 1:
305 convert_resizebilinear_1x1_to_add(op)
306 else:
307 convert_resizebilinear_to_2x2_pool(op)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200308
309 return op
310
311
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200312def convert_nop_split_to_identity(op, arch, nng):
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200313 if op.type == "Split" and op.attrs.get("num_splits") == 1:
314 # the list comprehension should return a list with a single tensor
315 # if it shouldn't, remove_passthrough_tensor will fail appropriately
316 op.inputs = [i for i in op.inputs if i.shape == op.outputs[0].shape]
317 op.type = "Identity"
318 return op
319
320
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200321def fixup_fully_connected_input(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100322 if op.type == "FullyConnectedAct":
323 inp = op.inputs[0]
324 weights = op.inputs[1]
325
326 n_in_elems = weights.shape[-2]
327 elms = inp.elements()
328 batch_size = elms // n_in_elems
329 assert batch_size * n_in_elems == elms
330
331 desired_shape = [batch_size, n_in_elems]
332 if inp.shape != desired_shape:
333 # mismatch, insert a reshape to fix this.
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200334 op.set_input_tensor(create_reshape_tensor(inp, desired_shape), 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100335
336 return op
337
338
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200339def convert_batched_fc_to_conv(op, arch, nng):
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200340 if op.type == "FullyConnectedAct":
341 ifm = op.inputs[0]
342 ofm = op.outputs[0]
343 # Check if the FC is 2D and first dimension indicates batching
344 if len(ifm.shape) == len(ofm.shape) == 2 and ifm.shape[0] != 1:
345 n = ifm.shape[0]
346 batching_split = {4: (2, 2), 8: (2, 4), 16: (4, 4)}
347 h, w = batching_split.get(n, (1, n))
348
349 # Convert to convolution
350 op.name += "_conv"
351 op.type = "Conv2DBiasAct"
352 faf = op.attrs.get("fused_activation_function", None)
353 op.attrs = {
354 "dilation": (1, 1, 1, 1),
355 "dilation_h_factor": 1,
356 "dilation_w_factor": 1,
357 "fused_activation_function": faf,
358 "npu_block_type": NpuBlockType.ConvolutionMxN,
359 "padding": b"SAME",
360 "stride_h": 1,
361 "stride_w": 1,
362 "strides": (1, 1, 1, 1),
363 }
364
365 prev_op = ifm.ops[0]
366 desired_shape = [1, h, w, ifm.shape[-1]]
367 if len(ifm.consumer_list) == 1 and prev_op is not None and prev_op.type == "Reshape":
368 # There is a preceding Reshape
369 # Compare input of prev_op and input of op, to see if prev_op can be removed
370 ifm_prev_op = prev_op.inputs[0]
371 if ifm_prev_op.shape == ifm.shape and ifm_prev_op.quantization.is_scaling_equal(ifm.quantization):
372 # prev_op can be removed
373 op.set_input_tensor(ifm_prev_op, 0)
374 else:
375 op.inputs[0].set_all_shapes(desired_shape)
376 prev_op.set_input_tensor(
377 create_const_tensor(prev_op.inputs[1].name, [1], DataType.int32, desired_shape), 1
378 )
379 prev_op.attrs["new_shape"] = desired_shape
380 else:
381 # Add reshape op to the input if there is no preceding reshape
382 ifm.consumer_list.remove(op)
383 op.set_input_tensor(create_reshape_tensor(ifm, desired_shape), 0)
384
385 # Reshape Weights to be 4D. IO becomes HWIO
386 weight_tensor = op.inputs[1]
387 weight_tensor.quant_values = np.expand_dims(np.expand_dims(weight_tensor.quant_values, axis=0), axis=0)
388 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
389
390 desired_shape = [1, h, w, ofm.shape[-1]]
391 if (
392 len(ofm.consumer_list) == 1
393 and ofm.consumer_list[0] is not None
394 and ofm.consumer_list[0].type == "Reshape"
395 ):
396 # There is a subsequent Reshape
397 # Compare desired shape and output of consumer op, to see if consumer op can be removed
398 ofm_cons_op = ofm.consumer_list[0].outputs[0]
399 if desired_shape == ofm_cons_op.shape and ofm.quantization.is_scaling_equal(ofm_cons_op.quantization):
400 op.outputs[0] = ofm_cons_op
401 op.outputs[0].ops = [op]
402 else:
403 op.outputs[0].set_all_shapes(desired_shape)
404 else:
405 # Add rehape op to the output
406 op.set_output_tensor(create_reshape_tensor(ofm, desired_shape, False))
407 return op
408
409
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200410def fixup_pack_input(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100411 if op.type == "Pack":
412 # Pack is also referred to as Stack
413 # Requires the rewrite_concat function to be called on the op afterwards
414 axis = int(op.attrs["axis"])
415 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
416
417 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100418 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100419
420 for idx, inp in enumerate(op.inputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100421 reshape_out = inp.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100422 reshape_out.set_all_shapes(desired_shape)
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100423
424 reshape_op = Operation("Reshape", "{}{}_reshape".format(op.name, idx))
425 reshape_op.attrs["new_shape"] = desired_shape
426 reshape_op.inputs = [inp, new_shape_tens]
427 reshape_op.set_output_tensor(reshape_out)
Tim Hall79d07d22020-04-27 18:20:16 +0100428
429 op.inputs[idx] = reshape_out
430
431 op.type = "PackReshaped"
432
433 return op
434
435
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200436def unfuse_activation_function(op, arch, nng):
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200437 unfuse_ops = ("ConcatTFLite",)
438 if op.type in unfuse_ops and op.run_on_npu and op.attrs.get("fused_activation_function", None) is not None:
439 act = op.attrs["fused_activation_function"]
440 del op.attrs["fused_activation_function"]
441 act_op = Operation(act, op.name + act)
442 out_tens = op.outputs[0]
443 intermediate_tens = out_tens.clone("_act_intermediate")
444 act_op.set_output_tensor(out_tens)
445 act_op.add_input_tensor(intermediate_tens)
446 op.set_output_tensor(intermediate_tens)
447
448 return op
449
Louis Verhaard8912c532020-09-30 12:11:49 +0200450
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200451def fixup_unpack_output(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100452 op = tens.ops[0]
453 if op.type in set(("Unpack", "StridedSlice")):
454 # Unpack is also referred to as Unstack
455 # Requires the rewrite_split function to be called on the op afterwards
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200456
457 reshape_input_shape = tens.shape
Tim Hall79d07d22020-04-27 18:20:16 +0100458 if op.type == "StridedSlice":
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200459 new_axis_mask = op.attrs["new_axis_mask"]
Tim Hall79d07d22020-04-27 18:20:16 +0100460 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Louis Verhaard7db78962020-05-25 15:05:26 +0200461 ellipsis_mask = op.attrs["ellipsis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200462
463 if (new_axis_mask != 0 and shrink_axis_mask != 0) or ellipsis_mask != 0:
464 # Not supported, will be put on CPU
465 return tens
466 if shrink_axis_mask == 0 and new_axis_mask == 0:
Tim Hall79d07d22020-04-27 18:20:16 +0100467 # Equal Rank StridedSlice, no need to insert reshape
468 return tens
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200469 elif shrink_axis_mask != 0:
470 n = 0
471 axis = 0
472 while shrink_axis_mask:
473 prev_mask = shrink_axis_mask
474 n += 1
475 shrink_axis_mask &= shrink_axis_mask - 1
476 axis = int(math.log2(prev_mask - shrink_axis_mask))
477 reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100478
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200479 assert len(tens.shape) == (len(op.inputs[0].shape) - n)
480 op.attrs["shrink_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100481
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200482 elif new_axis_mask != 0:
483 n = 0
484 axis = 0
485 while new_axis_mask:
486 prev_mask = new_axis_mask
487 n += 1
488 new_axis_mask &= new_axis_mask - 1
489 axis = int(math.log2(prev_mask - new_axis_mask))
Louis Verhaard7db78962020-05-25 15:05:26 +0200490 reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1) :]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200491 new_axis_mask >>= 1
492
493 assert len(tens.shape) == (len(op.inputs[0].shape) + n)
494 op.attrs["new_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100495 else:
496 axis = int(op.attrs["axis"])
497 op.type = "UnpackReshaped"
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200498 reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100499
500 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100501 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, tens.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100502
503 for idx, out_tens in enumerate(op.outputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100504 reshape_in = out_tens.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100505 reshape_in.set_all_shapes(reshape_input_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100506 reshape_in.ops = [op]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100507
508 reshape_op = Operation("Reshape", "{}{}_reshape".format(op.name, idx))
509 reshape_op.attrs["new_shape"] = reshape_input_shape
Tim Hall79d07d22020-04-27 18:20:16 +0100510 reshape_op.inputs = [reshape_in, new_shape_tens]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100511 reshape_op.set_output_tensor(out_tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100512
513 op.outputs[idx] = reshape_in
514
515 return tens
516
517
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200518def add_padding_fields(op, arch, nng):
Jacob Bohlin90033f32020-08-28 15:45:44 +0200519 if op.run_on_npu:
520 if "padding" in op.attrs:
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100521 if op.type in conv_op | depthwise_op:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200522 kernel_size = op.inputs[1].shape[:2]
523 input_shape = op.inputs[0].shape
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100524 elif op.type in pool_op | reduce_sum_ops:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200525 kernel_size = op.attrs["ksize"][1:3]
526 input_shape = op.inputs[0].shape
527 elif op.type == "ExtractImagePatches":
528 kernel_size = op.attrs["ksizes"][1:3]
529 input_shape = op.inputs[0].shape
530 else:
531 raise UnsupportedFeatureError("Unknown operation that uses padding: {}".format(op.type))
Tim Hall79d07d22020-04-27 18:20:16 +0100532
Jacob Bohlin90033f32020-08-28 15:45:44 +0200533 if op.type == "Conv2DBackpropInputSwitchedBias":
534 upscaling_factor = op.outputs[0].shape[1] // input_shape[1]
535 padding, skirt = calc_upscaled_padding_and_skirt(
536 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
537 )
538 else:
539 dilation_h, dilation_w = op.get_dilation_h_w()
540 dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1]
541 padding, skirt = calc_padding_and_skirt(
542 op.attrs["padding"], dilated_kernel_size, op.attrs["strides"], input_shape
543 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200544
Jacob Bohlin90033f32020-08-28 15:45:44 +0200545 op.attrs["explicit_padding"] = padding
546 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200547
Tim Hall79d07d22020-04-27 18:20:16 +0100548 return op
549
550
Tim Hall79d07d22020-04-27 18:20:16 +0100551# Check if the op can be reordered
552def get_prepend_op(op):
553 inp = op.inputs[0]
554 # The op should be reordered between prev_op and prep_op
555 prev_op = inp.ops[-1]
556 prep_op = None
557 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
558 prep_op = prev_op
559 inp = prev_op.inputs[0]
560 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100561 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 +0100562 return prep_op
563
564 return None
565
566
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200567def mark_npu_block_type(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100568 npu_block_type = NpuBlockType.Default
569 if op.type in conv_op:
570 npu_block_type = NpuBlockType.ConvolutionMxN
571 elif op.type in fc_op:
572 npu_block_type = NpuBlockType.VectorProduct
573 elif op.type in depthwise_op:
574 npu_block_type = NpuBlockType.ConvolutionDepthWise
575 elif op.type in pool_op:
576 npu_block_type = NpuBlockType.Pooling
577 elif op.type in elementwise_op:
578 npu_block_type = NpuBlockType.ElementWise
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200579 elif op.type in reduce_sum_ops:
580 npu_block_type = NpuBlockType.ReduceSum
Tim Hall79d07d22020-04-27 18:20:16 +0100581
582 op.attrs["npu_block_type"] = npu_block_type
583 return op
584
585
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200586def convert_depthwise_to_conv(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100587 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
588 # the ofm depth equals the depth multipler.
589 # If those conditions are true, then we can perform a simple
590 # switch of the operator type (and weight order)
591
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100592 if (op.type in depthwise_op) and (op.attrs["depth_multiplier"] != 1):
Tim Hall79d07d22020-04-27 18:20:16 +0100593 ifm_tensor = op.inputs[0]
594 weight_tensor = op.inputs[1]
595 ofm_tensor = op.outputs[0]
596 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
597 # Change op type to Conv2d
598 op.type = op.type.replace("DepthwiseConv2d", "Conv2D")
599 del op.attrs["channel_multiplier"]
600 del op.attrs["depth_multiplier"]
601
602 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100603 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100604 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200605 raise UnsupportedFeatureError(
606 "Unsupported DepthwiseConv2d with depth_multiplier = {}, ifm channels = {}, ofm channels = {}".format(
Tim Hall79d07d22020-04-27 18:20:16 +0100607 op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3]
608 )
609 )
Tim Hall79d07d22020-04-27 18:20:16 +0100610 return op
611
612
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200613def reorder_depthwise_weights(op, arch, nng):
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100614 if op.type in depthwise_op:
Jacob Bohline843d332020-06-23 12:12:56 +0200615 weight_tensor = op.inputs[1]
616 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100617 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200618 weight_tensor.weight_transpose_depthwise = True
619
620 return op
621
622
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200623def convert_conv_to_fc(op, arch, nng):
Michael McGeagh8d939c02020-07-29 13:11:43 +0100624 # Conv 1x1 can be equivalent to Fully Connected.
625 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
626 # caching/double buffering for the weights.
627 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
628 if op.type == "Conv2DBiasAct":
629 _, h, w, _ = op.inputs[0].shape
630 kh, kw, _, _ = op.inputs[1].shape
631 if h == 1 and w == 1 and kh == 1 and kw == 1:
632 # Overwrite this op as a Fully Connected Op
633 op.name += "_fc"
634 op.type = "FullyConnectedAct"
635 faf = op.attrs.get("fused_activation_function", None)
636 op.attrs = {
637 "fused_activation_function": faf,
638 "weights_format": 0,
639 "npu_block_type": NpuBlockType.VectorProduct,
640 }
641 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
642 weight_tensor = op.inputs[1]
643 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
644 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
645 # The output from a fully connected is expected to be 2D so we need to add a reshape layer to convert it
646 # back to 4D afterwards as the next layer is expecting that shape
647 orig_ofm_tensor = op.outputs[0]
648 # 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})
649 fc_ofm_tensor = orig_ofm_tensor.clone("_fc")
650 fc_ofm_tensor.set_all_shapes([1, fc_ofm_tensor.shape[-1]])
651 fc_ofm_tensor.ops = [op]
652 # Add a reshape after the new OFM to convert it back to the original 4D shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100653 reshape_name = op.name + "_reshape"
654 new_shape_tens = create_const_tensor(reshape_name + "_shape", [1], DataType.int32, orig_ofm_tensor.shape)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100655 reshape_op = Operation("Reshape", reshape_name)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100656 reshape_op.attrs["new_shape"] = orig_ofm_tensor.shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100657 reshape_op.inputs = [fc_ofm_tensor, new_shape_tens]
658 reshape_op.set_output_tensor(orig_ofm_tensor)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100659 # Replace this ops OFM to point to the 2D tensor
660 op.outputs[0] = fc_ofm_tensor
661 return op
662
663
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200664def fixup_relus_with_differing_ifm_ofm_scaling(op, arch, nng):
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100665 if op.run_on_npu and op.type in relu_ops:
666 ifm = op.inputs[0]
667 ofm = op.outputs[0]
668 # Relu with differing IFM and OFM scaling cannot be fused with another primary op
669 # and requires its own to be inserted
670 if not ifm.is_scaling_equal(ofm):
671 # Override this op with its own primary op (avgpool)
672 relu_fused_op = create_avgpool_nop(op.name + "_avgpool")
673 # And fuse the original activation function to it
674 relu_fused_op.attrs["fused_activation_function"] = op.type
675 # Tidy up and assign the ifm and ofm to the new op
676 ifm.consumer_list.remove(op)
Andreas Nevalainenf3d737e2020-09-25 14:12:43 +0200677
678 # if not 4d, reshape ifm/ofm
679 if len(ifm.shape) < 4:
680 ifm_shaped = create_reshape_tensor(ifm, full_shape(4, ifm.shape, 1))
681 ifm = ifm_shaped
682 if len(ofm.shape) < 4:
683 ofm_shaped = create_reshape_tensor(ofm, full_shape(4, ofm.shape, 1), False)
684 ofm = ofm_shaped
685
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100686 relu_fused_op.add_input_tensor(ifm)
687 relu_fused_op.set_output_tensor(ofm)
688 op = relu_fused_op
689 return op
690
691
Tim Hall79d07d22020-04-27 18:20:16 +0100692# Reorder activation op if it's after the memory only operations
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200693def fixup_act_reorder(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100694 if op.type in activation_ops:
695 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100696 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100697 act_op = op.clone("_reordered")
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200698
699 # There is only one input tensor, overwrite it
700 act_op.set_input_tensor(prep_op.inputs[0], 0)
701
Tim Hall79d07d22020-04-27 18:20:16 +0100702 act_op_out = act_op.inputs[0].clone("_acted")
703 act_op_out.quantization = op.outputs[0].quantization.clone()
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100704 act_op.set_output_tensor(act_op_out)
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200705
706 # Update the consumer list
707 act_op_out.consumer_list = op.outputs[0].consumer_list.copy()
708 act_op_out.consumer_list.append(prep_op)
709
Tim Hall79d07d22020-04-27 18:20:16 +0100710 prep_op.inputs[0] = act_op_out
711 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
712
713 # Mark the op so that it will be removed as passthrough later on
714 op.type = "Identity"
715 return op
716
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200717
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200718def fixup_elementwise_with_scalars(op, arch, nng):
Charles Xu78792222020-05-13 10:15:26 +0200719 if op.type in binary_elementwise_op:
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200720 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200721 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
722 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
723 if diff > 0:
724 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
725 elif diff < 0:
726 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200727 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
728 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
729 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
730 ifm_tensor.storage_shape = ifm_tensor.shape
731 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
732 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
733 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
734 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200735 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100736
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200737
Tim Hall4e127762020-05-15 16:05:49 +0100738# Set input/output tensor equivalence to the same id for memory operations
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200739def set_tensor_equivalence(op, arch, nng):
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100740 if op.type in memory_only_ops:
Tim Hall4e127762020-05-15 16:05:49 +0100741 eid = op.outputs[0].equivalence_id
742 for inp in op.inputs:
743 inp.equivalence_id = eid
744 return op
745
746
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200747def convert_softmax(op, arch, nng):
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200748 if op.type == "Softmax" and op.run_on_npu:
749 softmax = SoftMax(op)
750 op = softmax.get_graph()
751 return op
752
753
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200754def convert_mul_max_to_abs_or_lrelu(op, arch, nng):
Diego Russoea6111a2020-04-14 18:41:58 +0100755 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100756
757 Input X For X = -1 or X > 0
758 | \ / This subgraph can be replaced with either
759 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
760 | /
761 Max
762 """
763
764 if op.type == "Maximum":
765 # finds the Mul input(s) to the Max
766 muls = [i for i in op.inputs if i.ops[0].type == "MulAct"]
767 if len(muls) == 1:
768 mul = muls[0].ops[0]
769 elif len(muls) == 2:
770 # In the case both inputs are Muls, find the one with the same input as the Max
771 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
772 else:
773 # No Mul inputs
774 return op
775
776 # make sure the Mul doesn't have any other consumers
Louis Verhaardd7911c42020-08-25 13:36:41 +0200777 mul_ofm = mul.outputs[0]
778 if len(mul_ofm.consumers()) != 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100779 return op
780 # make sure the Mul doesn't have a faf
781 if mul.attrs["fused_activation_function"]:
782 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200783 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
784 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
785 return op
Louis Verhaardd7911c42020-08-25 13:36:41 +0200786 if not ifm.is_scaling_equal(ofm) or not ifm.is_scaling_equal(mul_ofm):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200787 # rewrite to LeakyRelu currently only makes sense if the quantization is identical
788 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100789
790 # finds the branched input that goes to both the Max and the Mul
791 shared = set(op.inputs) & set(mul.inputs)
792 if len(shared) == 1:
793 shared_in = shared.pop()
794 # find the constant scalar input to the Mul
795 const_tens = (set(mul.inputs) - {shared_in}).pop()
796 # check that it is a scalar
797 if const_tens.shape != []:
798 return op
799 const = const_tens.ops[0]
800 # check that it is a constant
801 if const.type != "Const":
802 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200803 # Remove the Mul from the shared input's consumers
804 shared_in.consumer_list.remove(mul)
Tim Hall79d07d22020-04-27 18:20:16 +0100805 else:
806 return op
807
808 val = const.outputs[0].values
809 if val >= 0:
810 new_op = "LeakyRelu"
811 op.attrs["alpha"] = val
Louis Verhaardd7911c42020-08-25 13:36:41 +0200812 # to produce bit exact results, the alpha is not enough;
813 # save additional scaling info in attr "alpha_scale", to be used as input
814 # to the LUT construction
815 alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point
816 mul_ifm_scale = np.double(ifm.quantization.scale_f32)
817 mul_ifm2_scale = np.double(const_tens.quantization.scale_f32)
818 mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32)
819 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale)
820 op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift)
Tim Hall79d07d22020-04-27 18:20:16 +0100821 elif val == -1:
822 new_op = "Abs"
823 else:
824 return op
825
826 op.type = op.type.replace("Maximum", new_op)
827 op.name = op.name.replace("Maximum", new_op)
828 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op)
829 op.inputs = [shared_in]
830 return op
831
832
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200833def convert_lrelu_to_mul_max(op, arch):
834 # Converts LeakyRelu to Max(alpha * IFM, identity * IFM)
835 # (the opposite of convert_mul_max_to_abs_or_lrelu)
836 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
837
838 # Add multiplication with alpha
839 mul_alpha = Operation("MulAct", op.name + "_mul_alpha")
840 mul_alpha.add_input_tensor(ifm)
841 # Create const tensor containing alpha as scalar
842 alpha = op.attrs["alpha"]
843 quantization = ifm.quantization.clone()
844 quantization.min = 0
845 quantization.max = alpha * (quantization.quant_max - quantization.quant_min)
846 quantization.scale_f32 = alpha
847 quantization.zero_point = 0
848 alpha_tens = create_const_tensor(op.name + "_alpha_scalar", [], ifm.dtype, [1], np.int8, quantization=quantization)
849 mul_alpha.add_input_tensor(alpha_tens)
850 fm_alpha = ofm.clone(op.name + "_alpha")
851 mul_alpha.set_output_tensor(fm_alpha)
852
853 if ifm.is_scaling_equal(ofm):
854 # No identity multiplication is needed
855 fm_id = ifm
856 else:
857 # Add multiplication with identity
858 mul_identity = Operation("MulAct", op.name + "_mul_identity")
859 mul_identity.add_input_tensor(ifm)
860 # Create const tensor containing identity as scalar
861 quantization = ifm.quantization.clone()
862 quantization.min = 0
863 quantization.max = quantization.quant_max - quantization.quant_min
864 quantization.scale_f32 = 1
865 quantization.zero_point = 0
866 identity_tens = create_const_tensor(
867 op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization
868 )
869 mul_identity.add_input_tensor(identity_tens)
870 fm_id = ofm.clone(op.name + "_id")
871 mul_identity.set_output_tensor(fm_id)
872
873 # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs
874 op.type = "Maximum"
875 op.name = op.name.replace("LeakyRelu", "Maximum")
876 op.inputs = []
877 ifm.consumer_list.remove(op)
878 op.add_input_tensor(fm_alpha)
879 op.add_input_tensor(fm_id)
880 return op
881
882
Louis Verhaardf03bad32020-09-25 08:30:44 +0200883def convert_to_lut(op, lut_values):
884 # Rewrite the operation by Add with scalar 0 + LUT activation
885 ifm = op.inputs[0]
Louis Verhaard58520b92020-08-24 16:45:38 +0200886 assert ifm.dtype.size_in_bytes() == 1
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200887 op.type = "AddAct"
888 op.name = op.name + "_add"
889 op.attrs.update({"npu_block_type": NpuBlockType.ElementWise})
890 # Mark as no-op to enable potential fusing optimizations
891 op.attrs["is_nop"] = True
892 # Create an input tensor containing scalar zero
893 quantization = QuantizationParameters(0.0, 255.0)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200894 quantization.scale_f32 = ifm.quantization.scale_f32
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200895 quantization.zero_point = 0
896 tens = create_const_tensor(op.inputs[0].name + "_add", [], ifm.dtype, [0], np.uint8, quantization=quantization)
897 op.add_input_tensor(tens)
Louis Verhaardf03bad32020-09-25 08:30:44 +0200898 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
899 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
900 # should be the same as the IFM
901 op.attrs["forced_output_quantization"] = ifm.quantization
902 lut_tensor = lut.create_lut_tensor(op.name + "_lut", lut_values, DataType.int8)
903 op.set_activation_lut(lut_tensor)
904 return op
905
906
907def convert_to_lut8(op, fn):
908 # Converts op to a no-op + int8/uint8 LUT which is generated with the given function.
909 # fn is a function(real) -> real
910 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
911 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
912 return op
913 # Generate the LUT
914 ifm_scale = np.double(ifm.quantization.scale_f32)
915 ofm_scale = np.double(ofm.quantization.scale_f32)
916 zp_in = ifm.quantization.zero_point
917 zp_out = ofm.quantization.zero_point
918 values = []
919 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
920 quantized_min = min(ix)
921 quantized_max = max(ix)
922 for x in ix:
923 x_real = ifm_scale * (x - zp_in)
924 y_real = fn(x_real)
925 lut_result = round_away_zero(zp_out + y_real / ofm_scale)
926 lut_result = min(quantized_max, max(quantized_min, lut_result))
927 values.append(lut_result)
928 return convert_to_lut(op, values)
929
930
931def convert_lrelu_to_lut(op, arch):
932 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200933 # Generate the LUT
Louis Verhaardd7911c42020-08-25 13:36:41 +0200934 alpha = op.attrs["alpha"]
935 ifm_scale = np.double(ifm.quantization.scale_f32)
936 ofm_scale = np.double(ofm.quantization.scale_f32)
937 zp_in = ifm.quantization.zero_point
938 zp_out = ofm.quantization.zero_point
939 identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale)
940 alpha_scalar = 1
941 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale)
942 if "alpha_scaling" in op.attrs:
943 # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu
944 alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"]
945 values = []
Louis Verhaard58520b92020-08-24 16:45:38 +0200946 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200947 quantized_min = min(ix)
948 quantized_max = max(ix)
949 for x in ix:
950 if x < zp_in:
951 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(
952 alpha_scalar * (x - zp_in), alpha_scale, alpha_shift
953 )
954 else:
955 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift)
956 lut_result = min(quantized_max, max(quantized_min, lut_result))
957 values.append(lut_result)
Louis Verhaardf03bad32020-09-25 08:30:44 +0200958 return convert_to_lut(op, values)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200959
960
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200961def convert_lrelu(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200962 # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max
963 if op.type != "LeakyRelu":
964 return op
965 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
Louis Verhaardd7911c42020-08-25 13:36:41 +0200966 if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype:
967 # use LUT for int8/uint8
968 return convert_lrelu_to_lut(op, arch)
969 if ifm.is_scaling_equal(ofm) and ifm.dtype == ofm.dtype and ifm.dtype == DataType.int16:
970 # use LeakyRelu unmodified for int16 with equal input/output scaling
971 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200972 return convert_lrelu_to_mul_max(op, arch)
973
974
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200975def convert_tanh_sigmoid_to_lut(op, arch, nng):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200976 # Converts int8/uint8 Sigmoid and Tanh to a LUT based solution
977 if op.type == "Sigmoid":
Louis Verhaard8912c532020-09-30 12:11:49 +0200978 return convert_to_lut8(op, clamp_sigmoid)
Louis Verhaardf03bad32020-09-25 08:30:44 +0200979 elif op.type == "Tanh":
980 return convert_to_lut8(op, math.tanh)
981 return op
982
983
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200984def remove_unwanted_reshapes(op, arch, nng):
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200985 # Try to remove reshapes enclosing ElementWise operator with only one non-constant input
986 if not op.run_on_npu or op.attrs["npu_block_type"] != NpuBlockType.ElementWise:
987 return op
988
989 # Check if the ElementWise operator only have one non-constant input
990 non_const_tens = [x for x in op.inputs if x.ops[0].type != "Const"]
991 if len(non_const_tens) != 1:
992 return op
993 ifm = non_const_tens[0]
994
995 # Check if operation is enclosed by Reshapes that can be removed
996 ofm = op.outputs[0]
997 prev_op = ifm.ops[0]
998 if (
999 len(ifm.consumer_list) == 1
1000 and prev_op.type == "Reshape"
1001 and len(ofm.consumer_list) == 1
1002 and ofm.consumer_list[0].type == "Reshape"
1003 ):
1004 # Operation is enclosed by reshapes, check if they can be removed
1005 prev_op_ifm, _, _, prev_op_ofm = prev_op.get_ifm_weights_biases_ofm()
1006 cons_op = ofm.consumer_list[0]
1007 cons_op_ifm = ofm
1008 cons_op_ofm = cons_op.outputs[0]
1009 if len(prev_op_ifm.shape) == len(cons_op_ofm.shape):
1010 # Check if quantization is the same in the input and output for the reshape ops
1011 if prev_op_ifm.quantization.is_scaling_equal(
1012 prev_op_ofm.quantization
1013 ) and cons_op_ifm.quantization.is_scaling_equal(cons_op_ofm.quantization):
Patrik Gustavsson7ad862a2020-09-29 14:09:43 +02001014 op.set_input_tensor(prev_op_ifm, 0)
1015 op.set_output_tensor(cons_op_ofm)
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001016 return op
1017
1018
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001019def fuse_activation_function_with_prev(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001020 # if op is a no-op: attempts to move the activation function to the preceding op
1021 if not op.attrs.get("is_nop", False) or op.attrs.get("fused_activation_function", None) is None:
1022 return op
1023 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
1024 # finds the input(s) to the operation
1025 prev_op = ifm.ops[0]
1026 # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed
1027 fuse = (
1028 prev_op.run_on_npu
Louis Verhaardf03bad32020-09-25 08:30:44 +02001029 and "npu_block_type" in prev_op.attrs
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001030 and prev_op.attrs["npu_block_type"] != NpuBlockType.Default
1031 and len(ifm.ops) == 1
1032 and len(prev_op.outputs[0].consumers()) == 1
1033 and prev_op.attrs.get("fused_activation_function", None) is None
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001034 )
1035 if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0:
1036 # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC),
1037 # LUT currently only works correctly for elementwise ops
1038 fuse = False
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001039 if not fuse:
1040 return op
1041 # Move the fused activation function + corresponding info to prev_op
Louis Verhaard98a34992020-09-01 10:39:04 +02001042 for attr in ("fused_activation_function", "forced_output_quantization"):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001043 if attr in op.attrs:
1044 prev_op.attrs[attr] = op.attrs[attr]
1045 if op.activation_lut is not None:
1046 prev_op.set_activation_lut(op.activation_lut)
1047 # Bypass op
Louis Verhaard98a34992020-09-01 10:39:04 +02001048 prev_op.set_output_tensor(ofm)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001049 return op
1050
1051
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001052def add_attrs_to_resizebilinear(op, arch, nng):
Tim Hallc30f4952020-06-15 20:47:35 +01001053 if op.type == "ResizeBilinear" and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +02001054 input_tensor = op.inputs[0]
1055 upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2]
1056 out_shape = op.outputs[0].shape[1:3]
1057 if not op.attrs["align_corners"] and out_shape == upscaled_shape:
1058 # this means the output is supposed to be a x2 upscale,
1059 # so we need to do SAME padding
1060 op.attrs["padding"] = b"SAME"
1061 elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]:
1062 # here we can just run the avg pool without padding and
1063 # produce a (M * 2 - 1, N * 2 - 1) sized output
1064 op.attrs["padding"] = b"VALID"
1065 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +02001066 return op
Dwight Lidman42fed942020-05-29 09:37:03 +02001067 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +01001068 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +02001069 return op
1070
1071
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001072def fixup_bias_tensors(op, arch, nng):
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001073 if op.needs_bias() and not op.inputs[-1]:
1074 # Op has no bias, add bias tensor filled with zeros
1075 nr_biases = op.inputs[1].shape[-1]
1076 bias_values = [0] * nr_biases
1077 bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values)
1078 bias_tensor.quant_values = bias_tensor.values
1079 op.set_input_tensor(bias_tensor, -1)
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +02001080
1081 return op
1082
1083
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001084def supported_operator_check(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +01001085 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
1086 return op
1087
1088
1089def optimise_graph_a(nng, arch, verbose_graph=False):
1090 if verbose_graph:
1091 nng.print_graph()
1092
1093 op_rewrite_list = [
1094 # mark block type and check if the operations are supported
1095 mark_npu_block_type,
Tim Hall4e127762020-05-15 16:05:49 +01001096 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +01001097 supported_operator_check,
1098 # then do any rewrites of supported operators
1099 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +01001100 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +02001101 convert_softmax,
Tim Hall79d07d22020-04-27 18:20:16 +01001102 fixup_fully_connected_input,
Patrik Gustavssoncb337042020-09-16 14:55:40 +02001103 convert_batched_fc_to_conv,
Tim Hall79d07d22020-04-27 18:20:16 +01001104 fixup_pack_input,
Fredrik Svedberg0f98b362020-09-29 10:00:39 +02001105 unfuse_activation_function,
Tim Hall79d07d22020-04-27 18:20:16 +01001106 fixup_conv2d_backprop,
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +01001107 fixup_relus_with_differing_ifm_ofm_scaling,
Tim Hall79d07d22020-04-27 18:20:16 +01001108 fixup_act_reorder,
Tim Hall79d07d22020-04-27 18:20:16 +01001109 mark_npu_block_type,
Charles Xu78792222020-05-13 10:15:26 +02001110 fixup_elementwise_with_scalars,
Jacob Bohline843d332020-06-23 12:12:56 +02001111 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +02001112 fixup_resizebilinear,
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001113 fixup_bias_tensors,
Dwight Lidmanc3862c22020-09-14 15:22:33 +02001114 convert_nop_split_to_identity,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001115 convert_mul_max_to_abs_or_lrelu,
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001116 remove_unwanted_reshapes,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001117 convert_lrelu,
Louis Verhaardf03bad32020-09-25 08:30:44 +02001118 convert_tanh_sigmoid_to_lut,
Tim Hall79d07d22020-04-27 18:20:16 +01001119 ]
1120
1121 for idx, sg in enumerate(nng.subgraphs):
1122 # rewrite graph pass
1123 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001124 nng, sg, arch, [fixup_unpack_output], op_rewrite_list, rewrite_unsupported=False
Tim Hall79d07d22020-04-27 18:20:16 +01001125 )
1126
1127 for idx, sg in enumerate(nng.subgraphs):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001128 # remove passthrough tensors and attempt further optimizations
1129 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001130 nng, sg, arch, [remove_passthrough_tensor], [fuse_activation_function_with_prev, add_padding_fields]
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001131 )
Tim Hall79d07d22020-04-27 18:20:16 +01001132
1133 if verbose_graph:
1134 nng.print_graph()
1135 return nng
1136
Diego Russoea6111a2020-04-14 18:41:58 +01001137
Tim Hall79d07d22020-04-27 18:20:16 +01001138def optimise_graph_b(nng, arch, verbose_graph=False):
1139 if verbose_graph:
1140 nng.print_graph()
1141
1142 for idx, sg in enumerate(nng.subgraphs):
1143 # combined rewrite graph pass
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001144 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(nng, sg, arch, [rewrite_concat, rewrite_split], [])
Tim Hall79d07d22020-04-27 18:20:16 +01001145
1146 if verbose_graph:
1147 nng.print_graph()
1148 return nng