blob: 48684058203aa0df7a0fc935c4368ba36d03b184 [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 Verhaarde0ef2732020-06-03 08:56:44 +020030from .numeric_util import full_shape
Diego Russoe8a10452020-04-21 17:39:10 +010031from .operation import NpuBlockType
32from .operation import Operation
Fredrik Svedberga0c36242020-06-03 15:43:31 +020033from .softmax import SoftMax
Michael McGeaghc5b549b2020-08-07 11:54:28 +010034from .tensor import create_const_tensor
35from .tensor import create_reshape_tensor
Charles Xu9a03fdf2020-07-02 15:12:40 +020036from .tensor import QuantizationParameters
Diego Russoe8a10452020-04-21 17:39:10 +010037from .tensor import Tensor
Tim Hall79d07d22020-04-27 18:20:16 +010038
39passthrough_nodes = set(("Identity",))
40
Michael McGeagh11b0bdb2020-09-08 11:07:35 +010041conv_op = set(("Conv2D", "QuantizedConv2D", "Conv2DBackpropInputSwitchedBias", "Conv2DBiasAct"))
42fc_op = set(
43 (
44 "MatMul",
45 "QuantizedMatMul",
46 "BlockLSTM",
47 "RnnAct",
48 "UnidirectionalSequenceRnnAct",
49 "BidirectionalSequenceRnnAct",
50 "LstmAct",
51 "UnidirectionalSequenceLstmAct",
52 "BidirectionalSequenceLstmAct",
53 "FullyConnectedAct",
54 )
55)
56depthwise_op = set(("DepthwiseConv2dNative", "DepthwiseConv2dBiasAct",))
57pool_op = set(
58 ("AvgPool", "MaxPool", "QuantizedAvgPool", "QuantizedMaxPool", "AvgPoolAct", "MaxPoolAct", "ResizeBilinear")
59)
60reduce_sum_ops = set(("ReduceSum",))
61binary_elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum"))
62elementwise_op = set(("LeakyRelu", "Abs", "CLZ", "SHL", "SHR")) | binary_elementwise_op
63relu_ops = set(("Relu", "Relu6", "ReluN1To1"))
64activation_ops = set(("Sigmoid", "Tanh")) | relu_ops
65memory_only_ops = set(("Reshape",))
66
Tim Hall79d07d22020-04-27 18:20:16 +010067
68def remove_passthrough_tensor(tens, arch):
69 if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes:
70 assert len(tens.ops[0].inputs) == 1
71 tens = tens.ops[0].inputs[0]
72 return tens
73
74
75def rewrite_concat(tens, arch):
76 if len(tens.ops) == 1 and tens.ops[0].is_concat_op():
77 concat_op = tens.ops[0]
78 if tens != concat_op.outputs[0]:
79 return tens # don't attempt to rewrite the min/max outputs of QuantizedConcat
80
81 # Not supported so leave it and run on CPU
82 if not concat_op.run_on_npu:
83 return tens
84
85 inputs, axis = concat_op.get_concat_inputs_axis()
86
87 tens.ops = []
88 offset = 0
89 for idx, inp in enumerate(inputs):
90 new_op = Operation("ConcatSliceWrite", concat_op.name + str(idx))
91 new_op.inputs = [inp]
92 new_op.outputs = [tens]
93 new_op.attrs["concat_axis"] = axis
94 new_op.attrs["concat_start"] = offset
95 offset += inp.shape[axis]
96 new_op.attrs["concat_end"] = offset
97 new_op.run_on_npu = True
98 tens.ops.append(new_op)
99 assert tens.shape[axis] == offset
100
Patrik Gustavsson29d568e2020-08-18 10:11:21 +0200101 # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a
102 # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte
103 # 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 +0200104 # and those addresses are always 16 byte aligned due to the NHCWB16 format.
Patrik Gustavsson29d568e2020-08-18 10:11:21 +0200105 if axis == (len(tens.shape) - 1):
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200106 for op in tens.ops:
107 if op.attrs["concat_start"] % 16 != 0:
108 tens.avoid_NHCWB16 = True
109 break
110
Tim Hall79d07d22020-04-27 18:20:16 +0100111 return tens
112
113
114def rewrite_split(tens, arch):
115
116 if len(tens.ops) == 1 and tens.ops[0].is_split_op():
117 split_op = tens.ops[0]
118
119 # Not supported so leave it and run on CPU
120 if not split_op.run_on_npu:
121 return tens
122
123 inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis()
124
125 tens.ops = []
126 new_op = Operation("SplitSliceRead", split_op.name)
127 new_op.inputs = [inp]
Tim Hall79d07d22020-04-27 18:20:16 +0100128
129 # For Split the offset cannot be extracted from the tensor so it has to
130 # be calculated from the index of the output tensor
Diego Russoea6111a2020-04-14 18:41:58 +0100131 if axis is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100132 # Get the start and end of the split
133 offset_start = [0] * len(tens.shape)
134 offset_end = [0] * len(tens.shape)
135 for out in outputs:
136 if out == tens:
137 break
138 offset_start[axis] += out.shape[axis]
139
Patrik Gustavssoneebb1c22020-08-18 15:03:04 +0200140 # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input
141 if (offset_start[-1] % 16) != 0:
142 inp.avoid_NHCWB16 = True
143
Tim Hall79d07d22020-04-27 18:20:16 +0100144 offset_end[axis] = offset_start[axis] + tens.shape[axis]
145
146 new_op.attrs["split_start"] = offset_start
147 new_op.attrs["split_end"] = offset_end
148 new_op.run_on_npu = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100149 new_op.set_output_tensor(tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100150
151 return tens
152
153
154def needed_total_padding(input_size, stride, filter_size):
155 out_size = (input_size + stride - 1) // stride
156 needed_input = (out_size - 1) * stride + filter_size
157 total_padding = max(0, needed_input - input_size)
158 return total_padding
159
160
161def calc_padding_and_skirt(padding_type, kernel_size, stride, input_dims):
162 ypad = needed_total_padding(int(input_dims[1]), int(stride[1]), int(kernel_size[0]))
163 xpad = needed_total_padding(int(input_dims[2]), int(stride[2]), int(kernel_size[1]))
164 if padding_type == b"SAME":
165 left_pad = (xpad + 0) // 2
166 right_pad = (xpad + 1) // 2
167 top_pad = (ypad + 0) // 2
168 bottom_pad = (ypad + 1) // 2
169 elif padding_type == b"VALID":
170 left_pad = 0
171 right_pad = 0
172 top_pad = 0
173 bottom_pad = 0
174 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200175 raise UnsupportedFeatureError("Unknown padding {}".format(str(padding_type)))
Tim Hall79d07d22020-04-27 18:20:16 +0100176 padding = (top_pad, left_pad, bottom_pad, right_pad)
177 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
178 return padding, skirt
179
Tim Hallc30f4952020-06-15 20:47:35 +0100180
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200181def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_dims, upscaling_factor):
182 kernel_height, kernel_width = kernel_size[0], kernel_size[1]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200183 if padding_type == b"SAME":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200184 ypad = needed_total_padding(int(input_dims[1]) * upscaling_factor, int(stride[1]), int(kernel_height))
185 xpad = needed_total_padding(int(input_dims[2]) * upscaling_factor, int(stride[2]), int(kernel_width))
186
Jacob Bohlind47cc272020-08-24 11:42:14 +0200187 right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0)
188 bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200189 left_pad = max(kernel_width - 1 - right_pad, 0)
190 top_pad = max(kernel_height - 1 - bottom_pad, 0)
191
Jacob Bohlincf7da102020-05-20 09:03:40 +0200192 elif padding_type == b"VALID":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200193 right_pad = max(kernel_width - 2, 0)
194 bottom_pad = max(kernel_height - 2, 0)
195 left_pad = kernel_width - 1
196 top_pad = kernel_height - 1
Jacob Bohlincf7da102020-05-20 09:03:40 +0200197 else:
198 assert 0, "Unknown padding"
199
200 padding = (top_pad, left_pad, bottom_pad, right_pad)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200201 skirt = padding
Jacob Bohlincf7da102020-05-20 09:03:40 +0200202 return padding, skirt
203
Tim Hall79d07d22020-04-27 18:20:16 +0100204
205def fixup_conv2d_backprop(op, arch):
206 if op.type == "Conv2DBackpropInput":
207 # flip the inputs
208 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200209 op.type = "Conv2DBackpropInputSwitchedBias"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200210
211 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100212 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100213
214 return op
215
216
Charles Xu9a03fdf2020-07-02 15:12:40 +0200217# Convert the op to an elementwise add
218def convert_resizebilinear_1x1_to_add(op):
219 op.type = "AddAct"
220 op.name = op.name + "_add"
221 op.attrs.update({"npu_block_type": NpuBlockType.ElementWise})
222 op.attrs["resizebilinear"] = True
223 # Create an input tensor filled with zeros
224 shape = op.outputs[0].shape
225 tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add")
226 tens.values = np.zeros(shape)
227 tens.quant_values = np.zeros(shape, np.uint8)
228 tens.quantization = QuantizationParameters(0.0, 255.0)
229 tens.quantization.scale_f32 = 1.0
230 tens.quantization.zero_point = 0
231 tens.consumer_list = [op]
232 tens_op = op.inputs[1].ops[0]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100233 tens_op.set_output_tensor(tens)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200234 # Set the add inputs
235 op.inputs[1] = op.inputs[0]
236 op.inputs[0] = tens
237
238 return op
239
240
Charles Xu87c13502020-08-06 12:17:26 +0200241# Convert ResizeBilinear to a number of 2x2 pool ops
242def convert_resizebilinear_to_2x2_pool(op):
243 count = 0
244 pre_op = op
245 outputs = op.outputs
246
247 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
248 if op.attrs["align_corners"]:
249 shape_modifier = 1
250 op.attrs["padding"] = b"VALID"
251 else:
252 shape_modifier = 0
253 op.attrs["padding"] = b"SAME"
254 op.inputs[0].resampling_mode = resampling_mode.NEAREST
255
256 upscaled_shape = np.array(op.inputs[0].shape[1:3])
257 out_shape = np.array(op.outputs[0].shape[1:3])
258 if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all():
259 return op
260
261 while (upscaled_shape < out_shape).all():
262 if count == 0:
263 scaled_op = pre_op
264 else:
265 scaled_op = op.clone("_{}".format(count))
266 scaled_op.inputs[0] = pre_op.outputs[0]
267
268 upscaled_shape = upscaled_shape * 2 - shape_modifier
269
270 if (upscaled_shape == out_shape).all():
271 scaled_op.outputs = outputs
272 scaled_op.outputs[0].ops = [scaled_op]
273 else:
274 shape = outputs[0].shape.copy()
275 shape[1:3] = upscaled_shape[0:2]
276 out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count))
277 out_tens.quantization = op.outputs[0].quantization.clone()
278 out_tens.quantization.quant_min = np.iinfo(np.int16).min
279 out_tens.quantization.quant_max = np.iinfo(np.int16).max
280 scaled_op.set_output_tensor(out_tens)
281 pre_op = scaled_op
282 count += 1
283
284 # Setup the scale value
285 if scaled_op.inputs[0].dtype.bits == 8 and scaled_op.outputs[0].dtype.bits == 16:
286 scaled_op.attrs["rescale"] = 128
287 elif scaled_op.inputs[0].dtype.bits == 16 and scaled_op.outputs[0].dtype.bits == 8:
288 scaled_op.attrs["rescale"] = 1 / 128
289 elif "rescale" in scaled_op.attrs:
290 del scaled_op.attrs["rescale"]
291
292 return op
293
294
Charles Xu9a03fdf2020-07-02 15:12:40 +0200295def fixup_resizebilinear(op, arch):
Charles Xu87c13502020-08-06 12:17:26 +0200296 if op.type == "ResizeBilinear" and op.run_on_npu:
297 if op.inputs[0].shape == op.outputs[0].shape:
Charles Xu36ffaf32020-08-05 15:40:44 +0200298 # Bypass nop resizebilinear
299 op.inputs = op.inputs[:1]
300 op.type = "Identity"
Charles Xu87c13502020-08-06 12:17:26 +0200301 elif op.inputs[0].shape[1] == 1 and op.inputs[0].shape[2] == 1:
302 convert_resizebilinear_1x1_to_add(op)
303 else:
304 convert_resizebilinear_to_2x2_pool(op)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200305
306 return op
307
308
Tim Hall79d07d22020-04-27 18:20:16 +0100309def fixup_fully_connected_input(op, arch):
310 if op.type == "FullyConnectedAct":
311 inp = op.inputs[0]
312 weights = op.inputs[1]
313
314 n_in_elems = weights.shape[-2]
315 elms = inp.elements()
316 batch_size = elms // n_in_elems
317 assert batch_size * n_in_elems == elms
318
319 desired_shape = [batch_size, n_in_elems]
320 if inp.shape != desired_shape:
321 # mismatch, insert a reshape to fix this.
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100322 op.inputs[0] = create_reshape_tensor(inp, desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100323
324 return op
325
326
327def fixup_pack_input(op, arch):
328 if op.type == "Pack":
329 # Pack is also referred to as Stack
330 # Requires the rewrite_concat function to be called on the op afterwards
331 axis = int(op.attrs["axis"])
332 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
333
334 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100335 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100336
337 for idx, inp in enumerate(op.inputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100338 reshape_out = inp.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100339 reshape_out.set_all_shapes(desired_shape)
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100340
341 reshape_op = Operation("Reshape", "{}{}_reshape".format(op.name, idx))
342 reshape_op.attrs["new_shape"] = desired_shape
343 reshape_op.inputs = [inp, new_shape_tens]
344 reshape_op.set_output_tensor(reshape_out)
Tim Hall79d07d22020-04-27 18:20:16 +0100345
346 op.inputs[idx] = reshape_out
347
348 op.type = "PackReshaped"
349
350 return op
351
352
353def fixup_unpack_output(tens, arch):
354 op = tens.ops[0]
355 if op.type in set(("Unpack", "StridedSlice")):
356 # Unpack is also referred to as Unstack
357 # Requires the rewrite_split function to be called on the op afterwards
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200358
359 reshape_input_shape = tens.shape
Tim Hall79d07d22020-04-27 18:20:16 +0100360 if op.type == "StridedSlice":
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200361 new_axis_mask = op.attrs["new_axis_mask"]
Tim Hall79d07d22020-04-27 18:20:16 +0100362 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Louis Verhaard7db78962020-05-25 15:05:26 +0200363 ellipsis_mask = op.attrs["ellipsis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200364
365 if (new_axis_mask != 0 and shrink_axis_mask != 0) or ellipsis_mask != 0:
366 # Not supported, will be put on CPU
367 return tens
368 if shrink_axis_mask == 0 and new_axis_mask == 0:
Tim Hall79d07d22020-04-27 18:20:16 +0100369 # Equal Rank StridedSlice, no need to insert reshape
370 return tens
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200371 elif shrink_axis_mask != 0:
372 n = 0
373 axis = 0
374 while shrink_axis_mask:
375 prev_mask = shrink_axis_mask
376 n += 1
377 shrink_axis_mask &= shrink_axis_mask - 1
378 axis = int(math.log2(prev_mask - shrink_axis_mask))
379 reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100380
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200381 assert len(tens.shape) == (len(op.inputs[0].shape) - n)
382 op.attrs["shrink_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100383
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200384 elif new_axis_mask != 0:
385 n = 0
386 axis = 0
387 while new_axis_mask:
388 prev_mask = new_axis_mask
389 n += 1
390 new_axis_mask &= new_axis_mask - 1
391 axis = int(math.log2(prev_mask - new_axis_mask))
Louis Verhaard7db78962020-05-25 15:05:26 +0200392 reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1) :]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200393 new_axis_mask >>= 1
394
395 assert len(tens.shape) == (len(op.inputs[0].shape) + n)
396 op.attrs["new_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100397 else:
398 axis = int(op.attrs["axis"])
399 op.type = "UnpackReshaped"
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200400 reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100401
402 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100403 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, tens.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100404
405 for idx, out_tens in enumerate(op.outputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100406 reshape_in = out_tens.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100407 reshape_in.set_all_shapes(reshape_input_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100408 reshape_in.ops = [op]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100409
410 reshape_op = Operation("Reshape", "{}{}_reshape".format(op.name, idx))
411 reshape_op.attrs["new_shape"] = reshape_input_shape
Tim Hall79d07d22020-04-27 18:20:16 +0100412 reshape_op.inputs = [reshape_in, new_shape_tens]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100413 reshape_op.set_output_tensor(out_tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100414
415 op.outputs[idx] = reshape_in
416
417 return tens
418
419
420def add_padding_fields(op, arch):
Jacob Bohlin90033f32020-08-28 15:45:44 +0200421 if op.run_on_npu:
422 if "padding" in op.attrs:
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100423 if op.type in conv_op | depthwise_op:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200424 kernel_size = op.inputs[1].shape[:2]
425 input_shape = op.inputs[0].shape
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100426 elif op.type in pool_op | reduce_sum_ops:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200427 kernel_size = op.attrs["ksize"][1:3]
428 input_shape = op.inputs[0].shape
429 elif op.type == "ExtractImagePatches":
430 kernel_size = op.attrs["ksizes"][1:3]
431 input_shape = op.inputs[0].shape
432 else:
433 raise UnsupportedFeatureError("Unknown operation that uses padding: {}".format(op.type))
Tim Hall79d07d22020-04-27 18:20:16 +0100434
Jacob Bohlin90033f32020-08-28 15:45:44 +0200435 if op.type == "Conv2DBackpropInputSwitchedBias":
436 upscaling_factor = op.outputs[0].shape[1] // input_shape[1]
437 padding, skirt = calc_upscaled_padding_and_skirt(
438 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
439 )
440 else:
441 dilation_h, dilation_w = op.get_dilation_h_w()
442 dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1]
443 padding, skirt = calc_padding_and_skirt(
444 op.attrs["padding"], dilated_kernel_size, op.attrs["strides"], input_shape
445 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200446
Jacob Bohlin90033f32020-08-28 15:45:44 +0200447 op.attrs["explicit_padding"] = padding
448 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200449
Tim Hall79d07d22020-04-27 18:20:16 +0100450 return op
451
452
Tim Hall79d07d22020-04-27 18:20:16 +0100453# Check if the op can be reordered
454def get_prepend_op(op):
455 inp = op.inputs[0]
456 # The op should be reordered between prev_op and prep_op
457 prev_op = inp.ops[-1]
458 prep_op = None
459 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
460 prep_op = prev_op
461 inp = prev_op.inputs[0]
462 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100463 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 +0100464 return prep_op
465
466 return None
467
468
469def mark_npu_block_type(op, arch):
470 npu_block_type = NpuBlockType.Default
471 if op.type in conv_op:
472 npu_block_type = NpuBlockType.ConvolutionMxN
473 elif op.type in fc_op:
474 npu_block_type = NpuBlockType.VectorProduct
475 elif op.type in depthwise_op:
476 npu_block_type = NpuBlockType.ConvolutionDepthWise
477 elif op.type in pool_op:
478 npu_block_type = NpuBlockType.Pooling
479 elif op.type in elementwise_op:
480 npu_block_type = NpuBlockType.ElementWise
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200481 elif op.type in reduce_sum_ops:
482 npu_block_type = NpuBlockType.ReduceSum
Tim Hall79d07d22020-04-27 18:20:16 +0100483
484 op.attrs["npu_block_type"] = npu_block_type
485 return op
486
487
488def convert_depthwise_to_conv(op, arch):
489 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
490 # the ofm depth equals the depth multipler.
491 # If those conditions are true, then we can perform a simple
492 # switch of the operator type (and weight order)
493
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100494 if (op.type in depthwise_op) and (op.attrs["depth_multiplier"] != 1):
Tim Hall79d07d22020-04-27 18:20:16 +0100495 ifm_tensor = op.inputs[0]
496 weight_tensor = op.inputs[1]
497 ofm_tensor = op.outputs[0]
498 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
499 # Change op type to Conv2d
500 op.type = op.type.replace("DepthwiseConv2d", "Conv2D")
501 del op.attrs["channel_multiplier"]
502 del op.attrs["depth_multiplier"]
503
504 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100505 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100506 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200507 raise UnsupportedFeatureError(
508 "Unsupported DepthwiseConv2d with depth_multiplier = {}, ifm channels = {}, ofm channels = {}".format(
Tim Hall79d07d22020-04-27 18:20:16 +0100509 op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3]
510 )
511 )
Tim Hall79d07d22020-04-27 18:20:16 +0100512 return op
513
514
Jacob Bohline843d332020-06-23 12:12:56 +0200515def reorder_depthwise_weights(op, arch):
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100516 if op.type in depthwise_op:
Jacob Bohline843d332020-06-23 12:12:56 +0200517 weight_tensor = op.inputs[1]
518 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100519 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200520 weight_tensor.weight_transpose_depthwise = True
521
522 return op
523
524
Michael McGeagh8d939c02020-07-29 13:11:43 +0100525def convert_conv_to_fc(op, arch):
526 # Conv 1x1 can be equivalent to Fully Connected.
527 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
528 # caching/double buffering for the weights.
529 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
530 if op.type == "Conv2DBiasAct":
531 _, h, w, _ = op.inputs[0].shape
532 kh, kw, _, _ = op.inputs[1].shape
533 if h == 1 and w == 1 and kh == 1 and kw == 1:
534 # Overwrite this op as a Fully Connected Op
535 op.name += "_fc"
536 op.type = "FullyConnectedAct"
537 faf = op.attrs.get("fused_activation_function", None)
538 op.attrs = {
539 "fused_activation_function": faf,
540 "weights_format": 0,
541 "npu_block_type": NpuBlockType.VectorProduct,
542 }
543 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
544 weight_tensor = op.inputs[1]
545 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
546 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
547 # The output from a fully connected is expected to be 2D so we need to add a reshape layer to convert it
548 # back to 4D afterwards as the next layer is expecting that shape
549 orig_ofm_tensor = op.outputs[0]
550 # 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})
551 fc_ofm_tensor = orig_ofm_tensor.clone("_fc")
552 fc_ofm_tensor.set_all_shapes([1, fc_ofm_tensor.shape[-1]])
553 fc_ofm_tensor.ops = [op]
554 # Add a reshape after the new OFM to convert it back to the original 4D shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100555 reshape_name = op.name + "_reshape"
556 new_shape_tens = create_const_tensor(reshape_name + "_shape", [1], DataType.int32, orig_ofm_tensor.shape)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100557 reshape_op = Operation("Reshape", reshape_name)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100558 reshape_op.attrs["new_shape"] = orig_ofm_tensor.shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100559 reshape_op.inputs = [fc_ofm_tensor, new_shape_tens]
560 reshape_op.set_output_tensor(orig_ofm_tensor)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100561 # Replace this ops OFM to point to the 2D tensor
562 op.outputs[0] = fc_ofm_tensor
563 return op
564
565
Tim Hall79d07d22020-04-27 18:20:16 +0100566# Reorder activation op if it's after the memory only operations
567def fixup_act_reorder(op, arch):
568 if op.type in activation_ops:
569 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100570 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100571 act_op = op.clone("_reordered")
572 act_op.inputs = [prep_op.inputs[0]]
573 act_op_out = act_op.inputs[0].clone("_acted")
574 act_op_out.quantization = op.outputs[0].quantization.clone()
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100575 act_op.set_output_tensor(act_op_out)
Tim Hall79d07d22020-04-27 18:20:16 +0100576 prep_op.inputs[0] = act_op_out
577 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
578
579 # Mark the op so that it will be removed as passthrough later on
580 op.type = "Identity"
581 return op
582
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200583
Charles Xu78792222020-05-13 10:15:26 +0200584def fixup_elementwise_with_scalars(op, arch):
585 if op.type in binary_elementwise_op:
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200586 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200587 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
588 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
589 if diff > 0:
590 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
591 elif diff < 0:
592 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200593 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
594 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
595 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
596 ifm_tensor.storage_shape = ifm_tensor.shape
597 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
598 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
599 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
600 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200601 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100602
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200603
Tim Hall4e127762020-05-15 16:05:49 +0100604# Set input/output tensor equivalence to the same id for memory operations
605def set_tensor_equivalence(op, arch):
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100606 if op.type in memory_only_ops:
Tim Hall4e127762020-05-15 16:05:49 +0100607 eid = op.outputs[0].equivalence_id
608 for inp in op.inputs:
609 inp.equivalence_id = eid
610 return op
611
612
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200613def convert_softmax(op, arch):
614 if op.type == "Softmax" and op.run_on_npu:
615 softmax = SoftMax(op)
616 op = softmax.get_graph()
617 return op
618
619
Tim Hall79d07d22020-04-27 18:20:16 +0100620def convert_mul_max_to_abs_or_lrelu(op, arch):
Diego Russoea6111a2020-04-14 18:41:58 +0100621 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100622
623 Input X For X = -1 or X > 0
624 | \ / This subgraph can be replaced with either
625 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
626 | /
627 Max
628 """
629
630 if op.type == "Maximum":
631 # finds the Mul input(s) to the Max
632 muls = [i for i in op.inputs if i.ops[0].type == "MulAct"]
633 if len(muls) == 1:
634 mul = muls[0].ops[0]
635 elif len(muls) == 2:
636 # In the case both inputs are Muls, find the one with the same input as the Max
637 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
638 else:
639 # No Mul inputs
640 return op
641
642 # make sure the Mul doesn't have any other consumers
Louis Verhaardd7911c42020-08-25 13:36:41 +0200643 mul_ofm = mul.outputs[0]
644 if len(mul_ofm.consumers()) != 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100645 return op
646 # make sure the Mul doesn't have a faf
647 if mul.attrs["fused_activation_function"]:
648 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200649 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
650 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
651 return op
Louis Verhaardd7911c42020-08-25 13:36:41 +0200652 if not ifm.is_scaling_equal(ofm) or not ifm.is_scaling_equal(mul_ofm):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200653 # rewrite to LeakyRelu currently only makes sense if the quantization is identical
654 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100655
656 # finds the branched input that goes to both the Max and the Mul
657 shared = set(op.inputs) & set(mul.inputs)
658 if len(shared) == 1:
659 shared_in = shared.pop()
660 # find the constant scalar input to the Mul
661 const_tens = (set(mul.inputs) - {shared_in}).pop()
662 # check that it is a scalar
663 if const_tens.shape != []:
664 return op
665 const = const_tens.ops[0]
666 # check that it is a constant
667 if const.type != "Const":
668 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200669 # Remove the Mul from the shared input's consumers
670 shared_in.consumer_list.remove(mul)
Tim Hall79d07d22020-04-27 18:20:16 +0100671 else:
672 return op
673
674 val = const.outputs[0].values
675 if val >= 0:
676 new_op = "LeakyRelu"
677 op.attrs["alpha"] = val
Louis Verhaardd7911c42020-08-25 13:36:41 +0200678 # to produce bit exact results, the alpha is not enough;
679 # save additional scaling info in attr "alpha_scale", to be used as input
680 # to the LUT construction
681 alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point
682 mul_ifm_scale = np.double(ifm.quantization.scale_f32)
683 mul_ifm2_scale = np.double(const_tens.quantization.scale_f32)
684 mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32)
685 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale)
686 op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift)
Tim Hall79d07d22020-04-27 18:20:16 +0100687 elif val == -1:
688 new_op = "Abs"
689 else:
690 return op
691
692 op.type = op.type.replace("Maximum", new_op)
693 op.name = op.name.replace("Maximum", new_op)
694 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op)
695 op.inputs = [shared_in]
696 return op
697
698
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200699def convert_lrelu_to_mul_max(op, arch):
700 # Converts LeakyRelu to Max(alpha * IFM, identity * IFM)
701 # (the opposite of convert_mul_max_to_abs_or_lrelu)
702 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
703
704 # Add multiplication with alpha
705 mul_alpha = Operation("MulAct", op.name + "_mul_alpha")
706 mul_alpha.add_input_tensor(ifm)
707 # Create const tensor containing alpha as scalar
708 alpha = op.attrs["alpha"]
709 quantization = ifm.quantization.clone()
710 quantization.min = 0
711 quantization.max = alpha * (quantization.quant_max - quantization.quant_min)
712 quantization.scale_f32 = alpha
713 quantization.zero_point = 0
714 alpha_tens = create_const_tensor(op.name + "_alpha_scalar", [], ifm.dtype, [1], np.int8, quantization=quantization)
715 mul_alpha.add_input_tensor(alpha_tens)
716 fm_alpha = ofm.clone(op.name + "_alpha")
717 mul_alpha.set_output_tensor(fm_alpha)
718
719 if ifm.is_scaling_equal(ofm):
720 # No identity multiplication is needed
721 fm_id = ifm
722 else:
723 # Add multiplication with identity
724 mul_identity = Operation("MulAct", op.name + "_mul_identity")
725 mul_identity.add_input_tensor(ifm)
726 # Create const tensor containing identity as scalar
727 quantization = ifm.quantization.clone()
728 quantization.min = 0
729 quantization.max = quantization.quant_max - quantization.quant_min
730 quantization.scale_f32 = 1
731 quantization.zero_point = 0
732 identity_tens = create_const_tensor(
733 op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization
734 )
735 mul_identity.add_input_tensor(identity_tens)
736 fm_id = ofm.clone(op.name + "_id")
737 mul_identity.set_output_tensor(fm_id)
738
739 # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs
740 op.type = "Maximum"
741 op.name = op.name.replace("LeakyRelu", "Maximum")
742 op.inputs = []
743 ifm.consumer_list.remove(op)
744 op.add_input_tensor(fm_alpha)
745 op.add_input_tensor(fm_id)
746 return op
747
748
749def convert_lrelu_to_lut(op, arch):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200750 # Rewrite LeakyRelu by Add with scalar 0 + LUT activation
Louis Verhaard58520b92020-08-24 16:45:38 +0200751 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
752 assert ifm.dtype.size_in_bytes() == 1
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200753 op.type = "AddAct"
754 op.name = op.name + "_add"
755 op.attrs.update({"npu_block_type": NpuBlockType.ElementWise})
756 # Mark as no-op to enable potential fusing optimizations
757 op.attrs["is_nop"] = True
758 # Create an input tensor containing scalar zero
759 quantization = QuantizationParameters(0.0, 255.0)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200760 quantization.scale_f32 = ifm.quantization.scale_f32
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200761 quantization.zero_point = 0
762 tens = create_const_tensor(op.inputs[0].name + "_add", [], ifm.dtype, [0], np.uint8, quantization=quantization)
763 op.add_input_tensor(tens)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200764 # Generate the LUT
Louis Verhaardd7911c42020-08-25 13:36:41 +0200765 alpha = op.attrs["alpha"]
766 ifm_scale = np.double(ifm.quantization.scale_f32)
767 ofm_scale = np.double(ofm.quantization.scale_f32)
768 zp_in = ifm.quantization.zero_point
769 zp_out = ofm.quantization.zero_point
770 identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale)
771 alpha_scalar = 1
772 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale)
773 if "alpha_scaling" in op.attrs:
774 # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu
775 alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"]
776 values = []
Louis Verhaard58520b92020-08-24 16:45:38 +0200777 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200778 quantized_min = min(ix)
779 quantized_max = max(ix)
780 for x in ix:
781 if x < zp_in:
782 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(
783 alpha_scalar * (x - zp_in), alpha_scale, alpha_shift
784 )
785 else:
786 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift)
787 lut_result = min(quantized_max, max(quantized_min, lut_result))
788 values.append(lut_result)
789 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
790 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
791 # should be the same as the IFM
792 op.attrs["forced_output_quantization"] = ifm.quantization
Louis Verhaard58520b92020-08-24 16:45:38 +0200793 lut_tensor = lut.create_lut_tensor(op.name + "_lut", values, DataType.int8)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200794 op.set_activation_lut(lut_tensor)
795 return op
796
797
798def convert_lrelu(op, arch):
799 # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max
800 if op.type != "LeakyRelu":
801 return op
802 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
Louis Verhaardd7911c42020-08-25 13:36:41 +0200803 if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype:
804 # use LUT for int8/uint8
805 return convert_lrelu_to_lut(op, arch)
806 if ifm.is_scaling_equal(ofm) and ifm.dtype == ofm.dtype and ifm.dtype == DataType.int16:
807 # use LeakyRelu unmodified for int16 with equal input/output scaling
808 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200809 return convert_lrelu_to_mul_max(op, arch)
810
811
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200812def remove_unwanted_reshapes(op, arch):
813 # Try to remove reshapes enclosing ElementWise operator with only one non-constant input
814 if not op.run_on_npu or op.attrs["npu_block_type"] != NpuBlockType.ElementWise:
815 return op
816
817 # Check if the ElementWise operator only have one non-constant input
818 non_const_tens = [x for x in op.inputs if x.ops[0].type != "Const"]
819 if len(non_const_tens) != 1:
820 return op
821 ifm = non_const_tens[0]
822
823 # Check if operation is enclosed by Reshapes that can be removed
824 ofm = op.outputs[0]
825 prev_op = ifm.ops[0]
826 if (
827 len(ifm.consumer_list) == 1
828 and prev_op.type == "Reshape"
829 and len(ofm.consumer_list) == 1
830 and ofm.consumer_list[0].type == "Reshape"
831 ):
832 # Operation is enclosed by reshapes, check if they can be removed
833 prev_op_ifm, _, _, prev_op_ofm = prev_op.get_ifm_weights_biases_ofm()
834 cons_op = ofm.consumer_list[0]
835 cons_op_ifm = ofm
836 cons_op_ofm = cons_op.outputs[0]
837 if len(prev_op_ifm.shape) == len(cons_op_ofm.shape):
838 # Check if quantization is the same in the input and output for the reshape ops
839 if prev_op_ifm.quantization.is_scaling_equal(
840 prev_op_ofm.quantization
841 ) and cons_op_ifm.quantization.is_scaling_equal(cons_op_ofm.quantization):
842 op.inputs[0] = prev_op_ifm
843 op.outputs[0] = cons_op_ofm
844 return op
845
846
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200847def fuse_activation_function_with_prev(op, arch):
848 # if op is a no-op: attempts to move the activation function to the preceding op
849 if not op.attrs.get("is_nop", False) or op.attrs.get("fused_activation_function", None) is None:
850 return op
851 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
852 # finds the input(s) to the operation
853 prev_op = ifm.ops[0]
854 # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed
855 fuse = (
856 prev_op.run_on_npu
857 and prev_op.attrs["npu_block_type"] != NpuBlockType.Default
858 and len(ifm.ops) == 1
859 and len(prev_op.outputs[0].consumers()) == 1
860 and prev_op.attrs.get("fused_activation_function", None) is None
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200861 )
862 if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0:
863 # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC),
864 # LUT currently only works correctly for elementwise ops
865 fuse = False
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200866 if not fuse:
867 return op
868 # Move the fused activation function + corresponding info to prev_op
Louis Verhaard98a34992020-09-01 10:39:04 +0200869 for attr in ("fused_activation_function", "forced_output_quantization"):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200870 if attr in op.attrs:
871 prev_op.attrs[attr] = op.attrs[attr]
872 if op.activation_lut is not None:
873 prev_op.set_activation_lut(op.activation_lut)
874 # Bypass op
Louis Verhaard98a34992020-09-01 10:39:04 +0200875 prev_op.set_output_tensor(ofm)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200876 return op
877
878
Dwight Lidman42fed942020-05-29 09:37:03 +0200879def add_attrs_to_resizebilinear(op, arch):
Tim Hallc30f4952020-06-15 20:47:35 +0100880 if op.type == "ResizeBilinear" and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +0200881 input_tensor = op.inputs[0]
882 upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2]
883 out_shape = op.outputs[0].shape[1:3]
884 if not op.attrs["align_corners"] and out_shape == upscaled_shape:
885 # this means the output is supposed to be a x2 upscale,
886 # so we need to do SAME padding
887 op.attrs["padding"] = b"SAME"
888 elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]:
889 # here we can just run the avg pool without padding and
890 # produce a (M * 2 - 1, N * 2 - 1) sized output
891 op.attrs["padding"] = b"VALID"
892 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +0200893 return op
Dwight Lidman42fed942020-05-29 09:37:03 +0200894 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +0100895 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +0200896 return op
897
898
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200899def fixup_bias_tensors(op, arch):
900 if op.needs_bias() and not op.inputs[-1]:
901 # Op has no bias, add bias tensor filled with zeros
902 nr_biases = op.inputs[1].shape[-1]
903 bias_values = [0] * nr_biases
904 bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values)
905 bias_tensor.quant_values = bias_tensor.values
906 op.set_input_tensor(bias_tensor, -1)
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200907
908 return op
909
910
Tim Hall79d07d22020-04-27 18:20:16 +0100911def supported_operator_check(op, arch):
912 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
913 return op
914
915
916def optimise_graph_a(nng, arch, verbose_graph=False):
917 if verbose_graph:
918 nng.print_graph()
919
920 op_rewrite_list = [
921 # mark block type and check if the operations are supported
922 mark_npu_block_type,
Tim Hall4e127762020-05-15 16:05:49 +0100923 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +0100924 supported_operator_check,
925 # then do any rewrites of supported operators
926 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +0100927 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200928 convert_softmax,
Tim Hall79d07d22020-04-27 18:20:16 +0100929 fixup_fully_connected_input,
930 fixup_pack_input,
931 fixup_conv2d_backprop,
932 fixup_act_reorder,
Tim Hall79d07d22020-04-27 18:20:16 +0100933 mark_npu_block_type,
Charles Xu78792222020-05-13 10:15:26 +0200934 fixup_elementwise_with_scalars,
Jacob Bohline843d332020-06-23 12:12:56 +0200935 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +0200936 fixup_resizebilinear,
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200937 fixup_bias_tensors,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200938 convert_mul_max_to_abs_or_lrelu,
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200939 remove_unwanted_reshapes,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200940 convert_lrelu,
Tim Hall79d07d22020-04-27 18:20:16 +0100941 ]
942
943 for idx, sg in enumerate(nng.subgraphs):
944 # rewrite graph pass
945 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Diego Russoea6111a2020-04-14 18:41:58 +0100946 sg, arch, [fixup_unpack_output], op_rewrite_list, rewrite_unsupported=False
Tim Hall79d07d22020-04-27 18:20:16 +0100947 )
948
949 for idx, sg in enumerate(nng.subgraphs):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200950 # remove passthrough tensors and attempt further optimizations
951 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Charles Xu87c13502020-08-06 12:17:26 +0200952 sg, arch, [remove_passthrough_tensor], [fuse_activation_function_with_prev, add_padding_fields]
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200953 )
Tim Hall79d07d22020-04-27 18:20:16 +0100954
955 if verbose_graph:
956 nng.print_graph()
957 return nng
958
Diego Russoea6111a2020-04-14 18:41:58 +0100959
Tim Hall79d07d22020-04-27 18:20:16 +0100960def optimise_graph_b(nng, arch, verbose_graph=False):
961 if verbose_graph:
962 nng.print_graph()
963
964 for idx, sg in enumerate(nng.subgraphs):
965 # combined rewrite graph pass
Diego Russoea6111a2020-04-14 18:41:58 +0100966 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [rewrite_concat, rewrite_split], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100967
968 if verbose_graph:
969 nng.print_graph()
970 return nng