blob: 46d26c80bb03f538671fcf76915f10e38a426058 [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 Verhaardb9fc33c2020-08-13 11:47:36 +020023from . import lut
Diego Russoea6111a2020-04-14 18:41:58 +010024from . import rewrite_graph
Diego Russoea6111a2020-04-14 18:41:58 +010025from .data_type import DataType
Louis Verhaard7db78962020-05-25 15:05:26 +020026from .errors import UnsupportedFeatureError
Dwight Lidman42fed942020-05-29 09:37:03 +020027from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Louis Verhaarde0ef2732020-06-03 08:56:44 +020028from .numeric_util import full_shape
Diego Russoe8a10452020-04-21 17:39:10 +010029from .operation import NpuBlockType
30from .operation import Operation
Fredrik Svedberga0c36242020-06-03 15:43:31 +020031from .softmax import SoftMax
Michael McGeaghc5b549b2020-08-07 11:54:28 +010032from .tensor import create_const_tensor
33from .tensor import create_reshape_tensor
Charles Xu9a03fdf2020-07-02 15:12:40 +020034from .tensor import QuantizationParameters
Diego Russoe8a10452020-04-21 17:39:10 +010035from .tensor import Tensor
Tim Hall79d07d22020-04-27 18:20:16 +010036
37passthrough_nodes = set(("Identity",))
38
39
40def remove_passthrough_tensor(tens, arch):
41 if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes:
42 assert len(tens.ops[0].inputs) == 1
43 tens = tens.ops[0].inputs[0]
44 return tens
45
46
47def rewrite_concat(tens, arch):
48 if len(tens.ops) == 1 and tens.ops[0].is_concat_op():
49 concat_op = tens.ops[0]
50 if tens != concat_op.outputs[0]:
51 return tens # don't attempt to rewrite the min/max outputs of QuantizedConcat
52
53 # Not supported so leave it and run on CPU
54 if not concat_op.run_on_npu:
55 return tens
56
57 inputs, axis = concat_op.get_concat_inputs_axis()
58
59 tens.ops = []
60 offset = 0
61 for idx, inp in enumerate(inputs):
62 new_op = Operation("ConcatSliceWrite", concat_op.name + str(idx))
63 new_op.inputs = [inp]
64 new_op.outputs = [tens]
65 new_op.attrs["concat_axis"] = axis
66 new_op.attrs["concat_start"] = offset
67 offset += inp.shape[axis]
68 new_op.attrs["concat_end"] = offset
69 new_op.run_on_npu = True
70 tens.ops.append(new_op)
71 assert tens.shape[axis] == offset
72
Patrik Gustavsson29d568e2020-08-18 10:11:21 +020073 # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a
74 # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte
75 # 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 +020076 # and those addresses are always 16 byte aligned due to the NHCWB16 format.
Patrik Gustavsson29d568e2020-08-18 10:11:21 +020077 if axis == (len(tens.shape) - 1):
Patrik Gustavsson458a2082020-08-13 13:41:05 +020078 for op in tens.ops:
79 if op.attrs["concat_start"] % 16 != 0:
80 tens.avoid_NHCWB16 = True
81 break
82
Tim Hall79d07d22020-04-27 18:20:16 +010083 return tens
84
85
86def rewrite_split(tens, arch):
87
88 if len(tens.ops) == 1 and tens.ops[0].is_split_op():
89 split_op = tens.ops[0]
90
91 # Not supported so leave it and run on CPU
92 if not split_op.run_on_npu:
93 return tens
94
95 inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis()
96
97 tens.ops = []
98 new_op = Operation("SplitSliceRead", split_op.name)
99 new_op.inputs = [inp]
Tim Hall79d07d22020-04-27 18:20:16 +0100100
101 # For Split the offset cannot be extracted from the tensor so it has to
102 # be calculated from the index of the output tensor
Diego Russoea6111a2020-04-14 18:41:58 +0100103 if axis is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100104 # Get the start and end of the split
105 offset_start = [0] * len(tens.shape)
106 offset_end = [0] * len(tens.shape)
107 for out in outputs:
108 if out == tens:
109 break
110 offset_start[axis] += out.shape[axis]
111
Patrik Gustavssoneebb1c22020-08-18 15:03:04 +0200112 # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input
113 if (offset_start[-1] % 16) != 0:
114 inp.avoid_NHCWB16 = True
115
Tim Hall79d07d22020-04-27 18:20:16 +0100116 offset_end[axis] = offset_start[axis] + tens.shape[axis]
117
118 new_op.attrs["split_start"] = offset_start
119 new_op.attrs["split_end"] = offset_end
120 new_op.run_on_npu = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100121 new_op.set_output_tensor(tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100122
123 return tens
124
125
126def needed_total_padding(input_size, stride, filter_size):
127 out_size = (input_size + stride - 1) // stride
128 needed_input = (out_size - 1) * stride + filter_size
129 total_padding = max(0, needed_input - input_size)
130 return total_padding
131
132
133def calc_padding_and_skirt(padding_type, kernel_size, stride, input_dims):
134 ypad = needed_total_padding(int(input_dims[1]), int(stride[1]), int(kernel_size[0]))
135 xpad = needed_total_padding(int(input_dims[2]), int(stride[2]), int(kernel_size[1]))
136 if padding_type == b"SAME":
137 left_pad = (xpad + 0) // 2
138 right_pad = (xpad + 1) // 2
139 top_pad = (ypad + 0) // 2
140 bottom_pad = (ypad + 1) // 2
141 elif padding_type == b"VALID":
142 left_pad = 0
143 right_pad = 0
144 top_pad = 0
145 bottom_pad = 0
146 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200147 raise UnsupportedFeatureError("Unknown padding {}".format(str(padding_type)))
Tim Hall79d07d22020-04-27 18:20:16 +0100148 padding = (top_pad, left_pad, bottom_pad, right_pad)
149 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
150 return padding, skirt
151
Tim Hallc30f4952020-06-15 20:47:35 +0100152
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200153def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_dims, upscaling_factor):
154 kernel_height, kernel_width = kernel_size[0], kernel_size[1]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200155 if padding_type == b"SAME":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200156 ypad = needed_total_padding(int(input_dims[1]) * upscaling_factor, int(stride[1]), int(kernel_height))
157 xpad = needed_total_padding(int(input_dims[2]) * upscaling_factor, int(stride[2]), int(kernel_width))
158
Jacob Bohlind47cc272020-08-24 11:42:14 +0200159 right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0)
160 bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200161 left_pad = max(kernel_width - 1 - right_pad, 0)
162 top_pad = max(kernel_height - 1 - bottom_pad, 0)
163
Jacob Bohlincf7da102020-05-20 09:03:40 +0200164 elif padding_type == b"VALID":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200165 right_pad = max(kernel_width - 2, 0)
166 bottom_pad = max(kernel_height - 2, 0)
167 left_pad = kernel_width - 1
168 top_pad = kernel_height - 1
Jacob Bohlincf7da102020-05-20 09:03:40 +0200169 else:
170 assert 0, "Unknown padding"
171
172 padding = (top_pad, left_pad, bottom_pad, right_pad)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200173 skirt = padding
Jacob Bohlincf7da102020-05-20 09:03:40 +0200174 return padding, skirt
175
Tim Hall79d07d22020-04-27 18:20:16 +0100176
177def fixup_conv2d_backprop(op, arch):
178 if op.type == "Conv2DBackpropInput":
179 # flip the inputs
180 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200181 op.type = "Conv2DBackpropInputSwitchedBias"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200182
183 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100184 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100185
186 return op
187
188
Charles Xu9a03fdf2020-07-02 15:12:40 +0200189# Convert the op to an elementwise add
190def convert_resizebilinear_1x1_to_add(op):
191 op.type = "AddAct"
192 op.name = op.name + "_add"
193 op.attrs.update({"npu_block_type": NpuBlockType.ElementWise})
194 op.attrs["resizebilinear"] = True
195 # Create an input tensor filled with zeros
196 shape = op.outputs[0].shape
197 tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add")
198 tens.values = np.zeros(shape)
199 tens.quant_values = np.zeros(shape, np.uint8)
200 tens.quantization = QuantizationParameters(0.0, 255.0)
201 tens.quantization.scale_f32 = 1.0
202 tens.quantization.zero_point = 0
203 tens.consumer_list = [op]
204 tens_op = op.inputs[1].ops[0]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100205 tens_op.set_output_tensor(tens)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200206 # Set the add inputs
207 op.inputs[1] = op.inputs[0]
208 op.inputs[0] = tens
209
210 return op
211
212
Charles Xu87c13502020-08-06 12:17:26 +0200213# Convert ResizeBilinear to a number of 2x2 pool ops
214def convert_resizebilinear_to_2x2_pool(op):
215 count = 0
216 pre_op = op
217 outputs = op.outputs
218
219 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
220 if op.attrs["align_corners"]:
221 shape_modifier = 1
222 op.attrs["padding"] = b"VALID"
223 else:
224 shape_modifier = 0
225 op.attrs["padding"] = b"SAME"
226 op.inputs[0].resampling_mode = resampling_mode.NEAREST
227
228 upscaled_shape = np.array(op.inputs[0].shape[1:3])
229 out_shape = np.array(op.outputs[0].shape[1:3])
230 if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all():
231 return op
232
233 while (upscaled_shape < out_shape).all():
234 if count == 0:
235 scaled_op = pre_op
236 else:
237 scaled_op = op.clone("_{}".format(count))
238 scaled_op.inputs[0] = pre_op.outputs[0]
239
240 upscaled_shape = upscaled_shape * 2 - shape_modifier
241
242 if (upscaled_shape == out_shape).all():
243 scaled_op.outputs = outputs
244 scaled_op.outputs[0].ops = [scaled_op]
245 else:
246 shape = outputs[0].shape.copy()
247 shape[1:3] = upscaled_shape[0:2]
248 out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count))
249 out_tens.quantization = op.outputs[0].quantization.clone()
250 out_tens.quantization.quant_min = np.iinfo(np.int16).min
251 out_tens.quantization.quant_max = np.iinfo(np.int16).max
252 scaled_op.set_output_tensor(out_tens)
253 pre_op = scaled_op
254 count += 1
255
256 # Setup the scale value
257 if scaled_op.inputs[0].dtype.bits == 8 and scaled_op.outputs[0].dtype.bits == 16:
258 scaled_op.attrs["rescale"] = 128
259 elif scaled_op.inputs[0].dtype.bits == 16 and scaled_op.outputs[0].dtype.bits == 8:
260 scaled_op.attrs["rescale"] = 1 / 128
261 elif "rescale" in scaled_op.attrs:
262 del scaled_op.attrs["rescale"]
263
264 return op
265
266
Charles Xu9a03fdf2020-07-02 15:12:40 +0200267def fixup_resizebilinear(op, arch):
Charles Xu87c13502020-08-06 12:17:26 +0200268 if op.type == "ResizeBilinear" and op.run_on_npu:
269 if op.inputs[0].shape == op.outputs[0].shape:
Charles Xu36ffaf32020-08-05 15:40:44 +0200270 # Bypass nop resizebilinear
271 op.inputs = op.inputs[:1]
272 op.type = "Identity"
Charles Xu87c13502020-08-06 12:17:26 +0200273 elif op.inputs[0].shape[1] == 1 and op.inputs[0].shape[2] == 1:
274 convert_resizebilinear_1x1_to_add(op)
275 else:
276 convert_resizebilinear_to_2x2_pool(op)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200277
278 return op
279
280
Tim Hall79d07d22020-04-27 18:20:16 +0100281def fixup_fully_connected_input(op, arch):
282 if op.type == "FullyConnectedAct":
283 inp = op.inputs[0]
284 weights = op.inputs[1]
285
286 n_in_elems = weights.shape[-2]
287 elms = inp.elements()
288 batch_size = elms // n_in_elems
289 assert batch_size * n_in_elems == elms
290
291 desired_shape = [batch_size, n_in_elems]
292 if inp.shape != desired_shape:
293 # mismatch, insert a reshape to fix this.
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100294 op.inputs[0] = create_reshape_tensor(inp, desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100295
296 return op
297
298
299def fixup_pack_input(op, arch):
300 if op.type == "Pack":
301 # Pack is also referred to as Stack
302 # Requires the rewrite_concat function to be called on the op afterwards
303 axis = int(op.attrs["axis"])
304 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
305
306 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100307 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100308
309 for idx, inp in enumerate(op.inputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100310 reshape_out = inp.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100311 reshape_out.set_all_shapes(desired_shape)
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100312
313 reshape_op = Operation("Reshape", "{}{}_reshape".format(op.name, idx))
314 reshape_op.attrs["new_shape"] = desired_shape
315 reshape_op.inputs = [inp, new_shape_tens]
316 reshape_op.set_output_tensor(reshape_out)
Tim Hall79d07d22020-04-27 18:20:16 +0100317
318 op.inputs[idx] = reshape_out
319
320 op.type = "PackReshaped"
321
322 return op
323
324
325def fixup_unpack_output(tens, arch):
326 op = tens.ops[0]
327 if op.type in set(("Unpack", "StridedSlice")):
328 # Unpack is also referred to as Unstack
329 # Requires the rewrite_split function to be called on the op afterwards
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200330
331 reshape_input_shape = tens.shape
Tim Hall79d07d22020-04-27 18:20:16 +0100332 if op.type == "StridedSlice":
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200333 new_axis_mask = op.attrs["new_axis_mask"]
Tim Hall79d07d22020-04-27 18:20:16 +0100334 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Louis Verhaard7db78962020-05-25 15:05:26 +0200335 ellipsis_mask = op.attrs["ellipsis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200336
337 if (new_axis_mask != 0 and shrink_axis_mask != 0) or ellipsis_mask != 0:
338 # Not supported, will be put on CPU
339 return tens
340 if shrink_axis_mask == 0 and new_axis_mask == 0:
Tim Hall79d07d22020-04-27 18:20:16 +0100341 # Equal Rank StridedSlice, no need to insert reshape
342 return tens
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200343 elif shrink_axis_mask != 0:
344 n = 0
345 axis = 0
346 while shrink_axis_mask:
347 prev_mask = shrink_axis_mask
348 n += 1
349 shrink_axis_mask &= shrink_axis_mask - 1
350 axis = int(math.log2(prev_mask - shrink_axis_mask))
351 reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100352
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200353 assert len(tens.shape) == (len(op.inputs[0].shape) - n)
354 op.attrs["shrink_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100355
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200356 elif new_axis_mask != 0:
357 n = 0
358 axis = 0
359 while new_axis_mask:
360 prev_mask = new_axis_mask
361 n += 1
362 new_axis_mask &= new_axis_mask - 1
363 axis = int(math.log2(prev_mask - new_axis_mask))
Louis Verhaard7db78962020-05-25 15:05:26 +0200364 reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1) :]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200365 new_axis_mask >>= 1
366
367 assert len(tens.shape) == (len(op.inputs[0].shape) + n)
368 op.attrs["new_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100369 else:
370 axis = int(op.attrs["axis"])
371 op.type = "UnpackReshaped"
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200372 reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100373
374 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100375 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, tens.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100376
377 for idx, out_tens in enumerate(op.outputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100378 reshape_in = out_tens.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100379 reshape_in.set_all_shapes(reshape_input_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100380 reshape_in.ops = [op]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100381
382 reshape_op = Operation("Reshape", "{}{}_reshape".format(op.name, idx))
383 reshape_op.attrs["new_shape"] = reshape_input_shape
Tim Hall79d07d22020-04-27 18:20:16 +0100384 reshape_op.inputs = [reshape_in, new_shape_tens]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100385 reshape_op.set_output_tensor(out_tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100386
387 op.outputs[idx] = reshape_in
388
389 return tens
390
391
392def add_padding_fields(op, arch):
393 if "padding" in op.attrs:
394 if "Conv" in op.type:
395 kernel_size = op.inputs[1].shape[:2]
396 input_shape = op.inputs[0].shape
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200397 elif "Pool" in op.type or op.type in ("ResizeBilinear", "ReduceSum"):
Tim Hall79d07d22020-04-27 18:20:16 +0100398 kernel_size = op.attrs["ksize"][1:3]
399 input_shape = op.inputs[0].shape
400 elif op.type == "ExtractImagePatches":
401 kernel_size = op.attrs["ksizes"][1:3]
402 input_shape = op.inputs[0].shape
403 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200404 raise UnsupportedFeatureError("Unknown operation that uses padding: {}".format(op.type))
Tim Hall79d07d22020-04-27 18:20:16 +0100405
Jacob Bohlincf7da102020-05-20 09:03:40 +0200406 if op.type == "Conv2DBackpropInputSwitchedBias":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200407 upscaling_factor = op.outputs[0].shape[1] // input_shape[1]
Tim Hallc30f4952020-06-15 20:47:35 +0100408 padding, skirt = calc_upscaled_padding_and_skirt(
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200409 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
Tim Hallc30f4952020-06-15 20:47:35 +0100410 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200411 else:
412 dilation_h, dilation_w = op.get_dilation_h_w()
413 dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1]
Tim Hallc30f4952020-06-15 20:47:35 +0100414 padding, skirt = calc_padding_and_skirt(
415 op.attrs["padding"], dilated_kernel_size, op.attrs["strides"], input_shape
416 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200417
Tim Hall79d07d22020-04-27 18:20:16 +0100418 op.attrs["explicit_padding"] = padding
419 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200420
Tim Hall79d07d22020-04-27 18:20:16 +0100421 return op
422
423
Jacob Bohlincf7da102020-05-20 09:03:40 +0200424conv_op = set(("Conv2D", "QuantizedConv2D", "Conv2DBackpropInputSwitchedBias", "Conv2DBiasAct"))
Tim Hall79d07d22020-04-27 18:20:16 +0100425fc_op = set(
426 (
427 "MatMul",
428 "QuantizedMatMul",
429 "BlockLSTM",
430 "RnnAct",
431 "UnidirectionalSequenceRnnAct",
432 "BidirectionalSequenceRnnAct",
433 "LstmAct",
434 "UnidirectionalSequenceLstmAct",
435 "BidirectionalSequenceLstmAct",
436 "FullyConnectedAct",
437 )
438)
439depthwise_op = set(("DepthwiseConv2dNative", "DepthwiseConv2dBiasAct",))
Louis Verhaard7db78962020-05-25 15:05:26 +0200440pool_op = set(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200441 ("AvgPool", "MaxPool", "QuantizedAvgPool", "QuantizedMaxPool", "AvgPoolAct", "MaxPoolAct", "ResizeBilinear")
Louis Verhaard7db78962020-05-25 15:05:26 +0200442)
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200443reduce_sum_ops = set(("ReduceSum",))
444elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum", "LeakyRelu", "Abs", "CLZ", "SHL", "SHR"))
Charles Xu78792222020-05-13 10:15:26 +0200445binary_elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum"))
Tim Hall79d07d22020-04-27 18:20:16 +0100446activation_ops = set(("Relu", "Relu6", "ReluN1To1", "Sigmoid", "Tanh"))
447memory_only_ops = set(("Reshape",))
448
Diego Russoea6111a2020-04-14 18:41:58 +0100449
Tim Hall79d07d22020-04-27 18:20:16 +0100450# Check if the op can be reordered
451def get_prepend_op(op):
452 inp = op.inputs[0]
453 # The op should be reordered between prev_op and prep_op
454 prev_op = inp.ops[-1]
455 prep_op = None
456 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
457 prep_op = prev_op
458 inp = prev_op.inputs[0]
459 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100460 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 +0100461 return prep_op
462
463 return None
464
465
466def mark_npu_block_type(op, arch):
467 npu_block_type = NpuBlockType.Default
468 if op.type in conv_op:
469 npu_block_type = NpuBlockType.ConvolutionMxN
470 elif op.type in fc_op:
471 npu_block_type = NpuBlockType.VectorProduct
472 elif op.type in depthwise_op:
473 npu_block_type = NpuBlockType.ConvolutionDepthWise
474 elif op.type in pool_op:
475 npu_block_type = NpuBlockType.Pooling
476 elif op.type in elementwise_op:
477 npu_block_type = NpuBlockType.ElementWise
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200478 elif op.type in reduce_sum_ops:
479 npu_block_type = NpuBlockType.ReduceSum
Tim Hall79d07d22020-04-27 18:20:16 +0100480
481 op.attrs["npu_block_type"] = npu_block_type
482 return op
483
484
485def convert_depthwise_to_conv(op, arch):
486 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
487 # the ofm depth equals the depth multipler.
488 # If those conditions are true, then we can perform a simple
489 # switch of the operator type (and weight order)
490
491 if ("DepthwiseConv2d" in op.type) and (op.attrs["depth_multiplier"] != 1):
492 ifm_tensor = op.inputs[0]
493 weight_tensor = op.inputs[1]
494 ofm_tensor = op.outputs[0]
495 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
496 # Change op type to Conv2d
497 op.type = op.type.replace("DepthwiseConv2d", "Conv2D")
498 del op.attrs["channel_multiplier"]
499 del op.attrs["depth_multiplier"]
500
501 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100502 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100503 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200504 raise UnsupportedFeatureError(
505 "Unsupported DepthwiseConv2d with depth_multiplier = {}, ifm channels = {}, ofm channels = {}".format(
Tim Hall79d07d22020-04-27 18:20:16 +0100506 op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3]
507 )
508 )
Tim Hall79d07d22020-04-27 18:20:16 +0100509 return op
510
511
Jacob Bohline843d332020-06-23 12:12:56 +0200512def reorder_depthwise_weights(op, arch):
513 if "DepthwiseConv2d" in op.type:
514 weight_tensor = op.inputs[1]
515 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100516 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200517 weight_tensor.weight_transpose_depthwise = True
518
519 return op
520
521
Michael McGeagh8d939c02020-07-29 13:11:43 +0100522def convert_conv_to_fc(op, arch):
523 # Conv 1x1 can be equivalent to Fully Connected.
524 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
525 # caching/double buffering for the weights.
526 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
527 if op.type == "Conv2DBiasAct":
528 _, h, w, _ = op.inputs[0].shape
529 kh, kw, _, _ = op.inputs[1].shape
530 if h == 1 and w == 1 and kh == 1 and kw == 1:
531 # Overwrite this op as a Fully Connected Op
532 op.name += "_fc"
533 op.type = "FullyConnectedAct"
534 faf = op.attrs.get("fused_activation_function", None)
535 op.attrs = {
536 "fused_activation_function": faf,
537 "weights_format": 0,
538 "npu_block_type": NpuBlockType.VectorProduct,
539 }
540 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
541 weight_tensor = op.inputs[1]
542 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
543 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
544 # The output from a fully connected is expected to be 2D so we need to add a reshape layer to convert it
545 # back to 4D afterwards as the next layer is expecting that shape
546 orig_ofm_tensor = op.outputs[0]
547 # 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})
548 fc_ofm_tensor = orig_ofm_tensor.clone("_fc")
549 fc_ofm_tensor.set_all_shapes([1, fc_ofm_tensor.shape[-1]])
550 fc_ofm_tensor.ops = [op]
551 # Add a reshape after the new OFM to convert it back to the original 4D shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100552 reshape_name = op.name + "_reshape"
553 new_shape_tens = create_const_tensor(reshape_name + "_shape", [1], DataType.int32, orig_ofm_tensor.shape)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100554 reshape_op = Operation("Reshape", reshape_name)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100555 reshape_op.attrs["new_shape"] = orig_ofm_tensor.shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100556 reshape_op.inputs = [fc_ofm_tensor, new_shape_tens]
557 reshape_op.set_output_tensor(orig_ofm_tensor)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100558 # Replace this ops OFM to point to the 2D tensor
559 op.outputs[0] = fc_ofm_tensor
560 return op
561
562
Tim Hall79d07d22020-04-27 18:20:16 +0100563# Reorder activation op if it's after the memory only operations
564def fixup_act_reorder(op, arch):
565 if op.type in activation_ops:
566 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100567 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100568 act_op = op.clone("_reordered")
569 act_op.inputs = [prep_op.inputs[0]]
570 act_op_out = act_op.inputs[0].clone("_acted")
571 act_op_out.quantization = op.outputs[0].quantization.clone()
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100572 act_op.set_output_tensor(act_op_out)
Tim Hall79d07d22020-04-27 18:20:16 +0100573 prep_op.inputs[0] = act_op_out
574 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
575
576 # Mark the op so that it will be removed as passthrough later on
577 op.type = "Identity"
578 return op
579
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200580
Charles Xu78792222020-05-13 10:15:26 +0200581def fixup_elementwise_with_scalars(op, arch):
582 if op.type in binary_elementwise_op:
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200583 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200584 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
585 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
586 if diff > 0:
587 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
588 elif diff < 0:
589 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200590 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
591 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
592 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
593 ifm_tensor.storage_shape = ifm_tensor.shape
594 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
595 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
596 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
597 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200598 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100599
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200600
Tim Hall4e127762020-05-15 16:05:49 +0100601# Set input/output tensor equivalence to the same id for memory operations
602def set_tensor_equivalence(op, arch):
603 if op.type == "Reshape":
604 eid = op.outputs[0].equivalence_id
605 for inp in op.inputs:
606 inp.equivalence_id = eid
607 return op
608
609
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200610def convert_softmax(op, arch):
611 if op.type == "Softmax" and op.run_on_npu:
612 softmax = SoftMax(op)
613 op = softmax.get_graph()
614 return op
615
616
Tim Hall79d07d22020-04-27 18:20:16 +0100617def convert_mul_max_to_abs_or_lrelu(op, arch):
Diego Russoea6111a2020-04-14 18:41:58 +0100618 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100619
620 Input X For X = -1 or X > 0
621 | \ / This subgraph can be replaced with either
622 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
623 | /
624 Max
625 """
626
627 if op.type == "Maximum":
628 # finds the Mul input(s) to the Max
629 muls = [i for i in op.inputs if i.ops[0].type == "MulAct"]
630 if len(muls) == 1:
631 mul = muls[0].ops[0]
632 elif len(muls) == 2:
633 # In the case both inputs are Muls, find the one with the same input as the Max
634 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
635 else:
636 # No Mul inputs
637 return op
638
639 # make sure the Mul doesn't have any other consumers
640 if len(mul.outputs[0].consumers()) != 1:
641 return op
642 # make sure the Mul doesn't have a faf
643 if mul.attrs["fused_activation_function"]:
644 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200645 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
646 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
647 return op
648 if not ifm.is_scaling_equal(ofm):
649 # rewrite to LeakyRelu currently only makes sense if the quantization is identical
650 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100651
652 # finds the branched input that goes to both the Max and the Mul
653 shared = set(op.inputs) & set(mul.inputs)
654 if len(shared) == 1:
655 shared_in = shared.pop()
656 # find the constant scalar input to the Mul
657 const_tens = (set(mul.inputs) - {shared_in}).pop()
658 # check that it is a scalar
659 if const_tens.shape != []:
660 return op
661 const = const_tens.ops[0]
662 # check that it is a constant
663 if const.type != "Const":
664 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200665 # Remove the Mul from the shared input's consumers
666 shared_in.consumer_list.remove(mul)
Tim Hall79d07d22020-04-27 18:20:16 +0100667 else:
668 return op
669
670 val = const.outputs[0].values
671 if val >= 0:
672 new_op = "LeakyRelu"
673 op.attrs["alpha"] = val
674 elif val == -1:
675 new_op = "Abs"
676 else:
677 return op
678
679 op.type = op.type.replace("Maximum", new_op)
680 op.name = op.name.replace("Maximum", new_op)
681 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op)
682 op.inputs = [shared_in]
683 return op
684
685
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200686def convert_lrelu_to_mul_max(op, arch):
687 # Converts LeakyRelu to Max(alpha * IFM, identity * IFM)
688 # (the opposite of convert_mul_max_to_abs_or_lrelu)
689 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
690
691 # Add multiplication with alpha
692 mul_alpha = Operation("MulAct", op.name + "_mul_alpha")
693 mul_alpha.add_input_tensor(ifm)
694 # Create const tensor containing alpha as scalar
695 alpha = op.attrs["alpha"]
696 quantization = ifm.quantization.clone()
697 quantization.min = 0
698 quantization.max = alpha * (quantization.quant_max - quantization.quant_min)
699 quantization.scale_f32 = alpha
700 quantization.zero_point = 0
701 alpha_tens = create_const_tensor(op.name + "_alpha_scalar", [], ifm.dtype, [1], np.int8, quantization=quantization)
702 mul_alpha.add_input_tensor(alpha_tens)
703 fm_alpha = ofm.clone(op.name + "_alpha")
704 mul_alpha.set_output_tensor(fm_alpha)
705
706 if ifm.is_scaling_equal(ofm):
707 # No identity multiplication is needed
708 fm_id = ifm
709 else:
710 # Add multiplication with identity
711 mul_identity = Operation("MulAct", op.name + "_mul_identity")
712 mul_identity.add_input_tensor(ifm)
713 # Create const tensor containing identity as scalar
714 quantization = ifm.quantization.clone()
715 quantization.min = 0
716 quantization.max = quantization.quant_max - quantization.quant_min
717 quantization.scale_f32 = 1
718 quantization.zero_point = 0
719 identity_tens = create_const_tensor(
720 op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization
721 )
722 mul_identity.add_input_tensor(identity_tens)
723 fm_id = ofm.clone(op.name + "_id")
724 mul_identity.set_output_tensor(fm_id)
725
726 # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs
727 op.type = "Maximum"
728 op.name = op.name.replace("LeakyRelu", "Maximum")
729 op.inputs = []
730 ifm.consumer_list.remove(op)
731 op.add_input_tensor(fm_alpha)
732 op.add_input_tensor(fm_id)
733 return op
734
735
736def convert_lrelu_to_lut(op, arch):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200737 # Rewrite LeakyRelu by Add with scalar 0 + LUT activation
Louis Verhaard58520b92020-08-24 16:45:38 +0200738 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
739 assert ifm.dtype.size_in_bytes() == 1
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200740 op.type = "AddAct"
741 op.name = op.name + "_add"
742 op.attrs.update({"npu_block_type": NpuBlockType.ElementWise})
743 # Mark as no-op to enable potential fusing optimizations
744 op.attrs["is_nop"] = True
745 # Create an input tensor containing scalar zero
746 quantization = QuantizationParameters(0.0, 255.0)
747 quantization.scale_f32 = 1.0
748 quantization.zero_point = 0
749 tens = create_const_tensor(op.inputs[0].name + "_add", [], ifm.dtype, [0], np.uint8, quantization=quantization)
750 op.add_input_tensor(tens)
751 alpha = op.attrs["alpha"]
752 zp = ofm.quantization.zero_point
753 # Generate the LUT
Louis Verhaard58520b92020-08-24 16:45:38 +0200754 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
755 values = [int(x) if x >= zp else int(round(zp - alpha * (zp - x))) for x in ix]
756 lut_tensor = lut.create_lut_tensor(op.name + "_lut", values, DataType.int8)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200757 op.set_activation_lut(lut_tensor)
758 return op
759
760
761def convert_lrelu(op, arch):
762 # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max
763 if op.type != "LeakyRelu":
764 return op
765 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
Louis Verhaard58520b92020-08-24 16:45:38 +0200766 if ifm.is_scaling_equal(ofm) and ifm.dtype == ofm.dtype:
767 if ifm.dtype in (DataType.uint8, DataType.int8):
768 # use LUT
769 return convert_lrelu_to_lut(op, arch)
770 elif ifm.dtype == DataType.int16:
771 # use LeakyRelu unmodified
772 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200773 return convert_lrelu_to_mul_max(op, arch)
774
775
776def fuse_activation_function_with_prev(op, arch):
777 # if op is a no-op: attempts to move the activation function to the preceding op
778 if not op.attrs.get("is_nop", False) or op.attrs.get("fused_activation_function", None) is None:
779 return op
780 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
781 # finds the input(s) to the operation
782 prev_op = ifm.ops[0]
783 # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed
784 fuse = (
785 prev_op.run_on_npu
786 and prev_op.attrs["npu_block_type"] != NpuBlockType.Default
787 and len(ifm.ops) == 1
788 and len(prev_op.outputs[0].consumers()) == 1
789 and prev_op.attrs.get("fused_activation_function", None) is None
790 and ifm.is_scaling_equal(ofm)
791 )
792 if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0:
793 # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC),
794 # LUT currently only works correctly for elementwise ops
795 fuse = False
796 if fuse and op.activation_lut is not None:
797 # Check if LUT can be used with prev_op
798 prev_ifm, prev_ifm2, _, _ = prev_op.get_ifm_ifm2_weights_ofm()
799 fuse = prev_ifm is not None and prev_ifm.quantization is not None and prev_ifm.is_scaling_equal(ifm)
800 if prev_ifm2 is not None:
801 fuse = fuse and prev_ifm2.quantization is not None and prev_ifm2.is_scaling_equal(ifm)
802 if not fuse:
803 return op
804 # Move the fused activation function + corresponding info to prev_op
805 for attr in ("fused_activation_function", "alpha"):
806 if attr in op.attrs:
807 prev_op.attrs[attr] = op.attrs[attr]
808 if op.activation_lut is not None:
809 prev_op.set_activation_lut(op.activation_lut)
810 # Bypass op
811 prev_op.set_output_tensor(op.outputs[0])
812 return op
813
814
Dwight Lidman42fed942020-05-29 09:37:03 +0200815def add_attrs_to_resizebilinear(op, arch):
Tim Hallc30f4952020-06-15 20:47:35 +0100816 if op.type == "ResizeBilinear" and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +0200817 input_tensor = op.inputs[0]
818 upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2]
819 out_shape = op.outputs[0].shape[1:3]
820 if not op.attrs["align_corners"] and out_shape == upscaled_shape:
821 # this means the output is supposed to be a x2 upscale,
822 # so we need to do SAME padding
823 op.attrs["padding"] = b"SAME"
824 elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]:
825 # here we can just run the avg pool without padding and
826 # produce a (M * 2 - 1, N * 2 - 1) sized output
827 op.attrs["padding"] = b"VALID"
828 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +0200829 return op
Dwight Lidman42fed942020-05-29 09:37:03 +0200830 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +0100831 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +0200832 return op
833
834
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200835def add_bias_tensor(op, arch):
Jacob Bohlind47cc272020-08-24 11:42:14 +0200836 if ("conv2d" in op.type.lower() or op.type.startswith("FullyConnected")) and not op.inputs[-1]:
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200837 # Add bias/scale tensor filled with zeros
838 weight_shape = op.inputs[1].shape
839 weight_sets = weight_shape[-1]
840 bias_values = [0] * weight_sets
841 scale_tens = create_const_tensor(op.name + "_bias", [weight_sets], DataType.int32, bias_values)
842 op.set_input_tensor(scale_tens, -1)
843
844 return op
845
846
Tim Hall79d07d22020-04-27 18:20:16 +0100847def supported_operator_check(op, arch):
848 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
849 return op
850
851
852def optimise_graph_a(nng, arch, verbose_graph=False):
853 if verbose_graph:
854 nng.print_graph()
855
856 op_rewrite_list = [
857 # mark block type and check if the operations are supported
858 mark_npu_block_type,
Tim Hall4e127762020-05-15 16:05:49 +0100859 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +0100860 supported_operator_check,
861 # then do any rewrites of supported operators
862 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +0100863 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200864 convert_softmax,
Tim Hall79d07d22020-04-27 18:20:16 +0100865 fixup_fully_connected_input,
866 fixup_pack_input,
867 fixup_conv2d_backprop,
868 fixup_act_reorder,
Tim Hall79d07d22020-04-27 18:20:16 +0100869 mark_npu_block_type,
Charles Xu78792222020-05-13 10:15:26 +0200870 fixup_elementwise_with_scalars,
Jacob Bohline843d332020-06-23 12:12:56 +0200871 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +0200872 fixup_resizebilinear,
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200873 add_bias_tensor,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200874 convert_mul_max_to_abs_or_lrelu,
875 convert_lrelu,
Tim Hall79d07d22020-04-27 18:20:16 +0100876 ]
877
878 for idx, sg in enumerate(nng.subgraphs):
879 # rewrite graph pass
880 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Diego Russoea6111a2020-04-14 18:41:58 +0100881 sg, arch, [fixup_unpack_output], op_rewrite_list, rewrite_unsupported=False
Tim Hall79d07d22020-04-27 18:20:16 +0100882 )
883
884 for idx, sg in enumerate(nng.subgraphs):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200885 # remove passthrough tensors and attempt further optimizations
886 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Charles Xu87c13502020-08-06 12:17:26 +0200887 sg, arch, [remove_passthrough_tensor], [fuse_activation_function_with_prev, add_padding_fields]
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200888 )
Tim Hall79d07d22020-04-27 18:20:16 +0100889
890 if verbose_graph:
891 nng.print_graph()
892 return nng
893
Diego Russoea6111a2020-04-14 18:41:58 +0100894
Tim Hall79d07d22020-04-27 18:20:16 +0100895def optimise_graph_b(nng, arch, verbose_graph=False):
896 if verbose_graph:
897 nng.print_graph()
898
899 for idx, sg in enumerate(nng.subgraphs):
900 # combined rewrite graph pass
Diego Russoea6111a2020-04-14 18:41:58 +0100901 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [rewrite_concat, rewrite_split], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100902
903 if verbose_graph:
904 nng.print_graph()
905 return nng