blob: 758b51a2cd5ec6e25910e2c4872baa3444c0257d [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
23from . import rewrite_graph
Diego Russoea6111a2020-04-14 18:41:58 +010024from .data_type import DataType
Louis Verhaard7db78962020-05-25 15:05:26 +020025from .errors import UnsupportedFeatureError
Dwight Lidman42fed942020-05-29 09:37:03 +020026from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Diego Russoe8a10452020-04-21 17:39:10 +010027from .operation import NpuBlockType
28from .operation import Operation
29from .tensor import Tensor
Charles Xu78792222020-05-13 10:15:26 +020030from .numeric_util import full_shape
Tim Hall79d07d22020-04-27 18:20:16 +010031
32passthrough_nodes = set(("Identity",))
33
34
35def remove_passthrough_tensor(tens, arch):
36 if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes:
37 assert len(tens.ops[0].inputs) == 1
38 tens = tens.ops[0].inputs[0]
39 return tens
40
41
42def rewrite_concat(tens, arch):
43 if len(tens.ops) == 1 and tens.ops[0].is_concat_op():
44 concat_op = tens.ops[0]
45 if tens != concat_op.outputs[0]:
46 return tens # don't attempt to rewrite the min/max outputs of QuantizedConcat
47
48 # Not supported so leave it and run on CPU
49 if not concat_op.run_on_npu:
50 return tens
51
52 inputs, axis = concat_op.get_concat_inputs_axis()
53
54 tens.ops = []
55 offset = 0
56 for idx, inp in enumerate(inputs):
57 new_op = Operation("ConcatSliceWrite", concat_op.name + str(idx))
58 new_op.inputs = [inp]
59 new_op.outputs = [tens]
60 new_op.attrs["concat_axis"] = axis
61 new_op.attrs["concat_start"] = offset
62 offset += inp.shape[axis]
63 new_op.attrs["concat_end"] = offset
64 new_op.run_on_npu = True
65 tens.ops.append(new_op)
66 assert tens.shape[axis] == offset
67
68 return tens
69
70
71def rewrite_split(tens, arch):
72
73 if len(tens.ops) == 1 and tens.ops[0].is_split_op():
74 split_op = tens.ops[0]
75
76 # Not supported so leave it and run on CPU
77 if not split_op.run_on_npu:
78 return tens
79
80 inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis()
81
82 tens.ops = []
83 new_op = Operation("SplitSliceRead", split_op.name)
84 new_op.inputs = [inp]
85 new_op.outputs = [tens]
86
87 # For Split the offset cannot be extracted from the tensor so it has to
88 # be calculated from the index of the output tensor
Diego Russoea6111a2020-04-14 18:41:58 +010089 if axis is not None:
Tim Hall79d07d22020-04-27 18:20:16 +010090 # Get the start and end of the split
91 offset_start = [0] * len(tens.shape)
92 offset_end = [0] * len(tens.shape)
93 for out in outputs:
94 if out == tens:
95 break
96 offset_start[axis] += out.shape[axis]
97
98 offset_end[axis] = offset_start[axis] + tens.shape[axis]
99
100 new_op.attrs["split_start"] = offset_start
101 new_op.attrs["split_end"] = offset_end
102 new_op.run_on_npu = True
103 tens.ops.append(new_op)
104
105 return tens
106
107
108def needed_total_padding(input_size, stride, filter_size):
109 out_size = (input_size + stride - 1) // stride
110 needed_input = (out_size - 1) * stride + filter_size
111 total_padding = max(0, needed_input - input_size)
112 return total_padding
113
114
115def calc_padding_and_skirt(padding_type, kernel_size, stride, input_dims):
116 ypad = needed_total_padding(int(input_dims[1]), int(stride[1]), int(kernel_size[0]))
117 xpad = needed_total_padding(int(input_dims[2]), int(stride[2]), int(kernel_size[1]))
118 if padding_type == b"SAME":
119 left_pad = (xpad + 0) // 2
120 right_pad = (xpad + 1) // 2
121 top_pad = (ypad + 0) // 2
122 bottom_pad = (ypad + 1) // 2
123 elif padding_type == b"VALID":
124 left_pad = 0
125 right_pad = 0
126 top_pad = 0
127 bottom_pad = 0
128 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200129 raise UnsupportedFeatureError("Unknown padding {}".format(str(padding_type)))
Tim Hall79d07d22020-04-27 18:20:16 +0100130 padding = (top_pad, left_pad, bottom_pad, right_pad)
131 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
132 return padding, skirt
133
134
135def fixup_conv2d_backprop(op, arch):
136 if op.type == "Conv2DBackpropInput":
137 # flip the inputs
138 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
139 op.type = "Conv2DBackpropInputSwitched"
140
141 return op
142
143
144def fixup_fully_connected_input(op, arch):
145 if op.type == "FullyConnectedAct":
146 inp = op.inputs[0]
147 weights = op.inputs[1]
148
149 n_in_elems = weights.shape[-2]
150 elms = inp.elements()
151 batch_size = elms // n_in_elems
152 assert batch_size * n_in_elems == elms
153
154 desired_shape = [batch_size, n_in_elems]
155 if inp.shape != desired_shape:
156 # mismatch, insert a reshape to fix this.
157 reshape_name = op.name + "_reshape"
158 new_shape_tens = Tensor([1], DataType.int32, reshape_name + "_shape")
159 new_shape_tens.values = np.array(desired_shape)
160 new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const")
161 new_shape_tens.ops = [new_shape_tens_const]
162 new_shape_tens_const.outputs = [new_shape_tens]
163
164 reshape_op = Operation("Reshape", reshape_name)
165 reshape_op.inputs = [inp, new_shape_tens]
166 reshape_op.attrs["new_shape"] = desired_shape
167 reshape_out = inp.clone("_reshaped")
168 reshape_out.shape = reshape_out.storage_shape = reshape_out.bandwidth_shape = desired_shape
169 reshape_out.ops = [reshape_op]
170 reshape_op.outputs = [reshape_out]
171
172 op.inputs[0] = reshape_out
173
174 return op
175
176
177def fixup_pack_input(op, arch):
178 if op.type == "Pack":
179 # Pack is also referred to as Stack
180 # Requires the rewrite_concat function to be called on the op afterwards
181 axis = int(op.attrs["axis"])
182 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
183
184 # Construct 1 shape tensor to be used by all inserted reshape ops
185 new_shape_name = op.name + "_reshape_shape"
186 new_shape_tens = Tensor([1], DataType.int32, new_shape_name)
187 new_shape_tens.values = np.array(desired_shape)
188 new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const")
189 new_shape_tens.ops = [new_shape_tens_const]
190 new_shape_tens_const.outputs = [new_shape_tens]
191
192 for idx, inp in enumerate(op.inputs):
193 reshape_name = op.name + str(idx) + "_reshape"
194 reshape_op = Operation("Reshape", reshape_name)
195 reshape_op.inputs = [inp, new_shape_tens]
196 reshape_op.attrs["new_shape"] = desired_shape
197 reshape_out = inp.clone("_reshaped")
198 reshape_out.shape = reshape_out.storage_shape = reshape_out.bandwidth_shape = desired_shape
199 reshape_out.ops = [reshape_op]
200 reshape_op.outputs = [reshape_out]
201
202 op.inputs[idx] = reshape_out
203
204 op.type = "PackReshaped"
205
206 return op
207
208
209def fixup_unpack_output(tens, arch):
210 op = tens.ops[0]
211 if op.type in set(("Unpack", "StridedSlice")):
212 # Unpack is also referred to as Unstack
213 # Requires the rewrite_split function to be called on the op afterwards
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200214
215 reshape_input_shape = tens.shape
Tim Hall79d07d22020-04-27 18:20:16 +0100216 if op.type == "StridedSlice":
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200217 new_axis_mask = op.attrs["new_axis_mask"]
Tim Hall79d07d22020-04-27 18:20:16 +0100218 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Louis Verhaard7db78962020-05-25 15:05:26 +0200219 ellipsis_mask = op.attrs["ellipsis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200220
221 if (new_axis_mask != 0 and shrink_axis_mask != 0) or ellipsis_mask != 0:
222 # Not supported, will be put on CPU
223 return tens
224 if shrink_axis_mask == 0 and new_axis_mask == 0:
Tim Hall79d07d22020-04-27 18:20:16 +0100225 # Equal Rank StridedSlice, no need to insert reshape
226 return tens
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200227 elif shrink_axis_mask != 0:
228 n = 0
229 axis = 0
230 while shrink_axis_mask:
231 prev_mask = shrink_axis_mask
232 n += 1
233 shrink_axis_mask &= shrink_axis_mask - 1
234 axis = int(math.log2(prev_mask - shrink_axis_mask))
235 reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100236
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200237 assert len(tens.shape) == (len(op.inputs[0].shape) - n)
238 op.attrs["shrink_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100239
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200240 elif new_axis_mask != 0:
241 n = 0
242 axis = 0
243 while new_axis_mask:
244 prev_mask = new_axis_mask
245 n += 1
246 new_axis_mask &= new_axis_mask - 1
247 axis = int(math.log2(prev_mask - new_axis_mask))
Louis Verhaard7db78962020-05-25 15:05:26 +0200248 reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1) :]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200249 new_axis_mask >>= 1
250
251 assert len(tens.shape) == (len(op.inputs[0].shape) + n)
252 op.attrs["new_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100253 else:
254 axis = int(op.attrs["axis"])
255 op.type = "UnpackReshaped"
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200256 reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100257
258 # Construct 1 shape tensor to be used by all inserted reshape ops
259 new_shape_name = op.name + "_reshape_shape"
260 new_shape_tens = Tensor([1], DataType.int32, new_shape_name)
261 new_shape_tens.values = np.array(tens.shape)
262 new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const")
263 new_shape_tens.ops = [new_shape_tens_const]
264 new_shape_tens_const.outputs = [new_shape_tens]
265
266 for idx, out_tens in enumerate(op.outputs):
267 reshape_name = op.name + str(idx) + "_reshape"
268 reshape_op = Operation("Reshape", reshape_name)
269 reshape_op.outputs = [out_tens]
270 reshape_in = out_tens.clone("_reshaped")
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200271 reshape_in.shape = reshape_in.storage_shape = reshape_in.bandwidth_shape = reshape_input_shape
Tim Hall79d07d22020-04-27 18:20:16 +0100272 reshape_in.ops = [op]
273 out_tens.ops = [reshape_op]
274 reshape_op.inputs = [reshape_in, new_shape_tens]
275
276 op.outputs[idx] = reshape_in
277
278 return tens
279
280
281def add_padding_fields(op, arch):
282 if "padding" in op.attrs:
283 if "Conv" in op.type:
284 kernel_size = op.inputs[1].shape[:2]
285 input_shape = op.inputs[0].shape
Dwight Lidman3ec04ac2020-04-30 11:54:48 +0200286 elif "Pool" in op.type or "ResizeBilinear" == op.type:
Tim Hall79d07d22020-04-27 18:20:16 +0100287 kernel_size = op.attrs["ksize"][1:3]
288 input_shape = op.inputs[0].shape
289 elif op.type == "ExtractImagePatches":
290 kernel_size = op.attrs["ksizes"][1:3]
291 input_shape = op.inputs[0].shape
292 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200293 raise UnsupportedFeatureError("Unknown operation that uses padding: {}".format(op.type))
Tim Hall79d07d22020-04-27 18:20:16 +0100294
295 padding, skirt = calc_padding_and_skirt(op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape)
296 op.attrs["explicit_padding"] = padding
297 op.attrs["skirt"] = skirt
298 return op
299
300
301conv_op = set(("Conv2D", "QuantizedConv2D", "Conv2DBackpropInputSwitched", "Conv2DBiasAct"))
302fc_op = set(
303 (
304 "MatMul",
305 "QuantizedMatMul",
306 "BlockLSTM",
307 "RnnAct",
308 "UnidirectionalSequenceRnnAct",
309 "BidirectionalSequenceRnnAct",
310 "LstmAct",
311 "UnidirectionalSequenceLstmAct",
312 "BidirectionalSequenceLstmAct",
313 "FullyConnectedAct",
314 )
315)
316depthwise_op = set(("DepthwiseConv2dNative", "DepthwiseConv2dBiasAct",))
Louis Verhaard7db78962020-05-25 15:05:26 +0200317pool_op = set(
318 ("AvgPool", "MaxPool", "QuantizedAvgPool", "QuantizedMaxPool", "AvgPoolAct", "MaxPoolAct", "ResizeBilinear",)
319)
Tim Hall79d07d22020-04-27 18:20:16 +0100320elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum", "LeakyRelu", "Abs"))
Charles Xu78792222020-05-13 10:15:26 +0200321binary_elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum"))
Tim Hall79d07d22020-04-27 18:20:16 +0100322activation_ops = set(("Relu", "Relu6", "ReluN1To1", "Sigmoid", "Tanh"))
323memory_only_ops = set(("Reshape",))
324
Diego Russoea6111a2020-04-14 18:41:58 +0100325
Tim Hall79d07d22020-04-27 18:20:16 +0100326# Check if the op can be reordered
327def get_prepend_op(op):
328 inp = op.inputs[0]
329 # The op should be reordered between prev_op and prep_op
330 prev_op = inp.ops[-1]
331 prep_op = None
332 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
333 prep_op = prev_op
334 inp = prev_op.inputs[0]
335 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100336 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 +0100337 return prep_op
338
339 return None
340
341
342def mark_npu_block_type(op, arch):
343 npu_block_type = NpuBlockType.Default
344 if op.type in conv_op:
345 npu_block_type = NpuBlockType.ConvolutionMxN
346 elif op.type in fc_op:
347 npu_block_type = NpuBlockType.VectorProduct
348 elif op.type in depthwise_op:
349 npu_block_type = NpuBlockType.ConvolutionDepthWise
350 elif op.type in pool_op:
351 npu_block_type = NpuBlockType.Pooling
352 elif op.type in elementwise_op:
353 npu_block_type = NpuBlockType.ElementWise
354
355 op.attrs["npu_block_type"] = npu_block_type
356 return op
357
358
359def convert_depthwise_to_conv(op, arch):
360 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
361 # the ofm depth equals the depth multipler.
362 # If those conditions are true, then we can perform a simple
363 # switch of the operator type (and weight order)
364
365 if ("DepthwiseConv2d" in op.type) and (op.attrs["depth_multiplier"] != 1):
366 ifm_tensor = op.inputs[0]
367 weight_tensor = op.inputs[1]
368 ofm_tensor = op.outputs[0]
369 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
370 # Change op type to Conv2d
371 op.type = op.type.replace("DepthwiseConv2d", "Conv2D")
372 del op.attrs["channel_multiplier"]
373 del op.attrs["depth_multiplier"]
374
375 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
376 weight_tensor.shape = weight_tensor.storage_shape = weight_tensor.bandwidth_shape = list(
377 weight_tensor.quant_values.shape
378 )
379 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200380 raise UnsupportedFeatureError(
381 "Unsupported DepthwiseConv2d with depth_multiplier = {}, ifm channels = {}, ofm channels = {}".format(
Tim Hall79d07d22020-04-27 18:20:16 +0100382 op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3]
383 )
384 )
Tim Hall79d07d22020-04-27 18:20:16 +0100385 return op
386
387
388# Reorder activation op if it's after the memory only operations
389def fixup_act_reorder(op, arch):
390 if op.type in activation_ops:
391 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100392 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100393 act_op = op.clone("_reordered")
394 act_op.inputs = [prep_op.inputs[0]]
395 act_op_out = act_op.inputs[0].clone("_acted")
396 act_op_out.quantization = op.outputs[0].quantization.clone()
397 act_op_out.ops = [act_op]
398 act_op.outputs = [act_op_out]
399 prep_op.inputs[0] = act_op_out
400 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
401
402 # Mark the op so that it will be removed as passthrough later on
403 op.type = "Identity"
404 return op
405
Charles Xu78792222020-05-13 10:15:26 +0200406def fixup_elementwise_with_scalars(op, arch):
407 if op.type in binary_elementwise_op:
408 ifm_tensor, ifm2_tensor, _, ofm_tensor = op.get_ifm_ifm2_weights_ofm()
409 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
410 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
411 if diff > 0:
412 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
413 elif diff < 0:
414 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
415 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100416
Tim Hall4e127762020-05-15 16:05:49 +0100417# Set input/output tensor equivalence to the same id for memory operations
418def set_tensor_equivalence(op, arch):
419 if op.type == "Reshape":
420 eid = op.outputs[0].equivalence_id
421 for inp in op.inputs:
422 inp.equivalence_id = eid
423 return op
424
425
Tim Hall79d07d22020-04-27 18:20:16 +0100426def convert_mul_max_to_abs_or_lrelu(op, arch):
Diego Russoea6111a2020-04-14 18:41:58 +0100427 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100428
429 Input X For X = -1 or X > 0
430 | \ / This subgraph can be replaced with either
431 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
432 | /
433 Max
434 """
435
436 if op.type == "Maximum":
437 # finds the Mul input(s) to the Max
438 muls = [i for i in op.inputs if i.ops[0].type == "MulAct"]
439 if len(muls) == 1:
440 mul = muls[0].ops[0]
441 elif len(muls) == 2:
442 # In the case both inputs are Muls, find the one with the same input as the Max
443 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
444 else:
445 # No Mul inputs
446 return op
447
448 # make sure the Mul doesn't have any other consumers
449 if len(mul.outputs[0].consumers()) != 1:
450 return op
451 # make sure the Mul doesn't have a faf
452 if mul.attrs["fused_activation_function"]:
453 return op
454
455 # finds the branched input that goes to both the Max and the Mul
456 shared = set(op.inputs) & set(mul.inputs)
457 if len(shared) == 1:
458 shared_in = shared.pop()
459 # find the constant scalar input to the Mul
460 const_tens = (set(mul.inputs) - {shared_in}).pop()
461 # check that it is a scalar
462 if const_tens.shape != []:
463 return op
464 const = const_tens.ops[0]
465 # check that it is a constant
466 if const.type != "Const":
467 return op
468 else:
469 return op
470
471 val = const.outputs[0].values
472 if val >= 0:
473 new_op = "LeakyRelu"
474 op.attrs["alpha"] = val
475 elif val == -1:
476 new_op = "Abs"
477 else:
478 return op
479
480 op.type = op.type.replace("Maximum", new_op)
481 op.name = op.name.replace("Maximum", new_op)
482 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op)
483 op.inputs = [shared_in]
484 return op
485
486
Dwight Lidman42fed942020-05-29 09:37:03 +0200487def add_attrs_to_resizebilinear(op, arch):
488 if op.type == 'ResizeBilinear' and op.run_on_npu:
489 input_tensor = op.inputs[0]
490 upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2]
491 out_shape = op.outputs[0].shape[1:3]
492 if not op.attrs["align_corners"] and out_shape == upscaled_shape:
493 # this means the output is supposed to be a x2 upscale,
494 # so we need to do SAME padding
495 op.attrs["padding"] = b"SAME"
496 elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]:
497 # here we can just run the avg pool without padding and
498 # produce a (M * 2 - 1, N * 2 - 1) sized output
499 op.attrs["padding"] = b"VALID"
500 else:
501 # If this exception is raised, something is wrong with the supported op check
502 raise UnsupportedFeatureError("Unsupported upscaling factor")
503 input_tensor.resampling_mode = resampling_mode.NEAREST
504 op.attrs.update({
505 'strides': (1, 1, 1, 1),
506 'ksize': (1, 2, 2, 1),
507 })
508 return op
509
510
Tim Hall79d07d22020-04-27 18:20:16 +0100511def supported_operator_check(op, arch):
512 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
513 return op
514
515
516def optimise_graph_a(nng, arch, verbose_graph=False):
517 if verbose_graph:
518 nng.print_graph()
519
520 op_rewrite_list = [
521 # mark block type and check if the operations are supported
522 mark_npu_block_type,
Tim Hall4e127762020-05-15 16:05:49 +0100523 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +0100524 supported_operator_check,
525 # then do any rewrites of supported operators
526 convert_depthwise_to_conv,
527 fixup_fully_connected_input,
528 fixup_pack_input,
529 fixup_conv2d_backprop,
530 fixup_act_reorder,
Dwight Lidman42fed942020-05-29 09:37:03 +0200531 add_attrs_to_resizebilinear,
Tim Hall79d07d22020-04-27 18:20:16 +0100532 add_padding_fields,
533 mark_npu_block_type,
Charles Xu78792222020-05-13 10:15:26 +0200534 fixup_elementwise_with_scalars,
Tim Hall79d07d22020-04-27 18:20:16 +0100535 # convert_mul_max_to_abs_or_lrelu # TODO: enable optimisation once quantisation issues are resolved
536 ]
537
538 for idx, sg in enumerate(nng.subgraphs):
539 # rewrite graph pass
540 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Diego Russoea6111a2020-04-14 18:41:58 +0100541 sg, arch, [fixup_unpack_output], op_rewrite_list, rewrite_unsupported=False
Tim Hall79d07d22020-04-27 18:20:16 +0100542 )
543
544 for idx, sg in enumerate(nng.subgraphs):
545 # remove passthrough tensors
Diego Russoea6111a2020-04-14 18:41:58 +0100546 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [remove_passthrough_tensor], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100547
548 if verbose_graph:
549 nng.print_graph()
550 return nng
551
Diego Russoea6111a2020-04-14 18:41:58 +0100552
Tim Hall79d07d22020-04-27 18:20:16 +0100553def optimise_graph_b(nng, arch, verbose_graph=False):
554 if verbose_graph:
555 nng.print_graph()
556
557 for idx, sg in enumerate(nng.subgraphs):
558 # combined rewrite graph pass
Diego Russoea6111a2020-04-14 18:41:58 +0100559 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [rewrite_concat, rewrite_split], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100560
561 if verbose_graph:
562 nng.print_graph()
563 return nng