blob: ca8b89fc5e24e91e5e7f521ce38bcc0fc5da9caa [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
Jacob Bohlincf7da102020-05-20 09:03:40 +0200134def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_dims):
135 upscaled_shape = [input_dims[0], input_dims[1] * stride[1], input_dims[2] * stride[2], input_dims[3]]
136 ypad = needed_total_padding(int(upscaled_shape[1]), int(stride[1]), int(kernel_size[0]))
137 xpad = needed_total_padding(int(upscaled_shape[2]), int(stride[2]), int(kernel_size[1]))
138
139 if padding_type == b"SAME":
140 right_pad = ((xpad + 1) // 2) - 1
141 bottom_pad = ((ypad + 1) // 2) - 1
142 left_pad = max(kernel_size[0] - 1 - right_pad, 0)
143 top_pad = max(kernel_size[1] - 1 - bottom_pad, 0)
144 elif padding_type == b"VALID":
145 right_pad = (xpad + 1) // 2
146 bottom_pad = (ypad + 1) // 2
147 left_pad = max(kernel_size[0] - right_pad, 0)
148 top_pad = max(kernel_size[1] - bottom_pad, 0)
149 else:
150 assert 0, "Unknown padding"
151
152 padding = (top_pad, left_pad, bottom_pad, right_pad)
153 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
154 return padding, skirt
155
Tim Hall79d07d22020-04-27 18:20:16 +0100156
157def fixup_conv2d_backprop(op, arch):
158 if op.type == "Conv2DBackpropInput":
159 # flip the inputs
160 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200161 op.type = "Conv2DBackpropInputSwitchedBias"
162 weight_shape = op.inputs[1].shape
163 weight_sets = weight_shape[3]
164
165 if len(op.inputs) < 4:
166 # Add bias/scale tensor filled with zeros
167 scale_op = Operation("Const", op.name + "_bias")
168 scale_tens = Tensor([weight_sets], DataType.int32, op.name + "_bias_tens")
169 scale_tens.values = [0] * weight_sets
170 scale_tens.quant_values = [0] * weight_sets
171 scale_tens.ops = [scale_op]
172 scale_op.outputs = [scale_tens]
173 scale_tens.consumer_list = [op]
174 op.inputs.append(scale_tens)
175
176 # Update strides
177 op.attrs.update( {"stride_w": 1, "stride_h": 1, "strides": (1,1,1,1)} )
Tim Hall79d07d22020-04-27 18:20:16 +0100178
179 return op
180
181
182def fixup_fully_connected_input(op, arch):
183 if op.type == "FullyConnectedAct":
184 inp = op.inputs[0]
185 weights = op.inputs[1]
186
187 n_in_elems = weights.shape[-2]
188 elms = inp.elements()
189 batch_size = elms // n_in_elems
190 assert batch_size * n_in_elems == elms
191
192 desired_shape = [batch_size, n_in_elems]
193 if inp.shape != desired_shape:
194 # mismatch, insert a reshape to fix this.
195 reshape_name = op.name + "_reshape"
196 new_shape_tens = Tensor([1], DataType.int32, reshape_name + "_shape")
197 new_shape_tens.values = np.array(desired_shape)
198 new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const")
199 new_shape_tens.ops = [new_shape_tens_const]
200 new_shape_tens_const.outputs = [new_shape_tens]
201
202 reshape_op = Operation("Reshape", reshape_name)
203 reshape_op.inputs = [inp, new_shape_tens]
204 reshape_op.attrs["new_shape"] = desired_shape
205 reshape_out = inp.clone("_reshaped")
206 reshape_out.shape = reshape_out.storage_shape = reshape_out.bandwidth_shape = desired_shape
207 reshape_out.ops = [reshape_op]
208 reshape_op.outputs = [reshape_out]
209
210 op.inputs[0] = reshape_out
211
212 return op
213
214
215def fixup_pack_input(op, arch):
216 if op.type == "Pack":
217 # Pack is also referred to as Stack
218 # Requires the rewrite_concat function to be called on the op afterwards
219 axis = int(op.attrs["axis"])
220 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
221
222 # Construct 1 shape tensor to be used by all inserted reshape ops
223 new_shape_name = op.name + "_reshape_shape"
224 new_shape_tens = Tensor([1], DataType.int32, new_shape_name)
225 new_shape_tens.values = np.array(desired_shape)
226 new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const")
227 new_shape_tens.ops = [new_shape_tens_const]
228 new_shape_tens_const.outputs = [new_shape_tens]
229
230 for idx, inp in enumerate(op.inputs):
231 reshape_name = op.name + str(idx) + "_reshape"
232 reshape_op = Operation("Reshape", reshape_name)
233 reshape_op.inputs = [inp, new_shape_tens]
234 reshape_op.attrs["new_shape"] = desired_shape
235 reshape_out = inp.clone("_reshaped")
236 reshape_out.shape = reshape_out.storage_shape = reshape_out.bandwidth_shape = desired_shape
237 reshape_out.ops = [reshape_op]
238 reshape_op.outputs = [reshape_out]
239
240 op.inputs[idx] = reshape_out
241
242 op.type = "PackReshaped"
243
244 return op
245
246
247def fixup_unpack_output(tens, arch):
248 op = tens.ops[0]
249 if op.type in set(("Unpack", "StridedSlice")):
250 # Unpack is also referred to as Unstack
251 # Requires the rewrite_split function to be called on the op afterwards
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200252
253 reshape_input_shape = tens.shape
Tim Hall79d07d22020-04-27 18:20:16 +0100254 if op.type == "StridedSlice":
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200255 new_axis_mask = op.attrs["new_axis_mask"]
Tim Hall79d07d22020-04-27 18:20:16 +0100256 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Louis Verhaard7db78962020-05-25 15:05:26 +0200257 ellipsis_mask = op.attrs["ellipsis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200258
259 if (new_axis_mask != 0 and shrink_axis_mask != 0) or ellipsis_mask != 0:
260 # Not supported, will be put on CPU
261 return tens
262 if shrink_axis_mask == 0 and new_axis_mask == 0:
Tim Hall79d07d22020-04-27 18:20:16 +0100263 # Equal Rank StridedSlice, no need to insert reshape
264 return tens
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200265 elif shrink_axis_mask != 0:
266 n = 0
267 axis = 0
268 while shrink_axis_mask:
269 prev_mask = shrink_axis_mask
270 n += 1
271 shrink_axis_mask &= shrink_axis_mask - 1
272 axis = int(math.log2(prev_mask - shrink_axis_mask))
273 reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100274
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200275 assert len(tens.shape) == (len(op.inputs[0].shape) - n)
276 op.attrs["shrink_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100277
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200278 elif new_axis_mask != 0:
279 n = 0
280 axis = 0
281 while new_axis_mask:
282 prev_mask = new_axis_mask
283 n += 1
284 new_axis_mask &= new_axis_mask - 1
285 axis = int(math.log2(prev_mask - new_axis_mask))
Louis Verhaard7db78962020-05-25 15:05:26 +0200286 reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1) :]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200287 new_axis_mask >>= 1
288
289 assert len(tens.shape) == (len(op.inputs[0].shape) + n)
290 op.attrs["new_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100291 else:
292 axis = int(op.attrs["axis"])
293 op.type = "UnpackReshaped"
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200294 reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100295
296 # Construct 1 shape tensor to be used by all inserted reshape ops
297 new_shape_name = op.name + "_reshape_shape"
298 new_shape_tens = Tensor([1], DataType.int32, new_shape_name)
299 new_shape_tens.values = np.array(tens.shape)
300 new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const")
301 new_shape_tens.ops = [new_shape_tens_const]
302 new_shape_tens_const.outputs = [new_shape_tens]
303
304 for idx, out_tens in enumerate(op.outputs):
305 reshape_name = op.name + str(idx) + "_reshape"
306 reshape_op = Operation("Reshape", reshape_name)
307 reshape_op.outputs = [out_tens]
308 reshape_in = out_tens.clone("_reshaped")
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200309 reshape_in.shape = reshape_in.storage_shape = reshape_in.bandwidth_shape = reshape_input_shape
Tim Hall79d07d22020-04-27 18:20:16 +0100310 reshape_in.ops = [op]
311 out_tens.ops = [reshape_op]
312 reshape_op.inputs = [reshape_in, new_shape_tens]
313
314 op.outputs[idx] = reshape_in
315
316 return tens
317
318
319def add_padding_fields(op, arch):
320 if "padding" in op.attrs:
321 if "Conv" in op.type:
322 kernel_size = op.inputs[1].shape[:2]
323 input_shape = op.inputs[0].shape
Dwight Lidman3ec04ac2020-04-30 11:54:48 +0200324 elif "Pool" in op.type or "ResizeBilinear" == op.type:
Tim Hall79d07d22020-04-27 18:20:16 +0100325 kernel_size = op.attrs["ksize"][1:3]
326 input_shape = op.inputs[0].shape
327 elif op.type == "ExtractImagePatches":
328 kernel_size = op.attrs["ksizes"][1:3]
329 input_shape = op.inputs[0].shape
330 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200331 raise UnsupportedFeatureError("Unknown operation that uses padding: {}".format(op.type))
Tim Hall79d07d22020-04-27 18:20:16 +0100332
Jacob Bohlincf7da102020-05-20 09:03:40 +0200333 if op.type == "Conv2DBackpropInputSwitchedBias":
334 padding, skirt = calc_upscaled_padding_and_skirt(op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape)
335 else:
336 dilation_h, dilation_w = op.get_dilation_h_w()
337 dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1]
338 padding, skirt = calc_padding_and_skirt(op.attrs["padding"], dilated_kernel_size, op.attrs["strides"], input_shape)
339
Tim Hall79d07d22020-04-27 18:20:16 +0100340 op.attrs["explicit_padding"] = padding
341 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200342
Tim Hall79d07d22020-04-27 18:20:16 +0100343 return op
344
345
Jacob Bohlincf7da102020-05-20 09:03:40 +0200346conv_op = set(("Conv2D", "QuantizedConv2D", "Conv2DBackpropInputSwitchedBias", "Conv2DBiasAct"))
Tim Hall79d07d22020-04-27 18:20:16 +0100347fc_op = set(
348 (
349 "MatMul",
350 "QuantizedMatMul",
351 "BlockLSTM",
352 "RnnAct",
353 "UnidirectionalSequenceRnnAct",
354 "BidirectionalSequenceRnnAct",
355 "LstmAct",
356 "UnidirectionalSequenceLstmAct",
357 "BidirectionalSequenceLstmAct",
358 "FullyConnectedAct",
359 )
360)
361depthwise_op = set(("DepthwiseConv2dNative", "DepthwiseConv2dBiasAct",))
Louis Verhaard7db78962020-05-25 15:05:26 +0200362pool_op = set(
363 ("AvgPool", "MaxPool", "QuantizedAvgPool", "QuantizedMaxPool", "AvgPoolAct", "MaxPoolAct", "ResizeBilinear",)
364)
Tim Hall79d07d22020-04-27 18:20:16 +0100365elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum", "LeakyRelu", "Abs"))
Charles Xu78792222020-05-13 10:15:26 +0200366binary_elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum"))
Tim Hall79d07d22020-04-27 18:20:16 +0100367activation_ops = set(("Relu", "Relu6", "ReluN1To1", "Sigmoid", "Tanh"))
368memory_only_ops = set(("Reshape",))
369
Diego Russoea6111a2020-04-14 18:41:58 +0100370
Tim Hall79d07d22020-04-27 18:20:16 +0100371# Check if the op can be reordered
372def get_prepend_op(op):
373 inp = op.inputs[0]
374 # The op should be reordered between prev_op and prep_op
375 prev_op = inp.ops[-1]
376 prep_op = None
377 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
378 prep_op = prev_op
379 inp = prev_op.inputs[0]
380 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100381 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 +0100382 return prep_op
383
384 return None
385
386
387def mark_npu_block_type(op, arch):
388 npu_block_type = NpuBlockType.Default
389 if op.type in conv_op:
390 npu_block_type = NpuBlockType.ConvolutionMxN
391 elif op.type in fc_op:
392 npu_block_type = NpuBlockType.VectorProduct
393 elif op.type in depthwise_op:
394 npu_block_type = NpuBlockType.ConvolutionDepthWise
395 elif op.type in pool_op:
396 npu_block_type = NpuBlockType.Pooling
397 elif op.type in elementwise_op:
398 npu_block_type = NpuBlockType.ElementWise
399
400 op.attrs["npu_block_type"] = npu_block_type
401 return op
402
403
404def convert_depthwise_to_conv(op, arch):
405 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
406 # the ofm depth equals the depth multipler.
407 # If those conditions are true, then we can perform a simple
408 # switch of the operator type (and weight order)
409
410 if ("DepthwiseConv2d" in op.type) and (op.attrs["depth_multiplier"] != 1):
411 ifm_tensor = op.inputs[0]
412 weight_tensor = op.inputs[1]
413 ofm_tensor = op.outputs[0]
414 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
415 # Change op type to Conv2d
416 op.type = op.type.replace("DepthwiseConv2d", "Conv2D")
417 del op.attrs["channel_multiplier"]
418 del op.attrs["depth_multiplier"]
419
420 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
421 weight_tensor.shape = weight_tensor.storage_shape = weight_tensor.bandwidth_shape = list(
422 weight_tensor.quant_values.shape
423 )
424 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200425 raise UnsupportedFeatureError(
426 "Unsupported DepthwiseConv2d with depth_multiplier = {}, ifm channels = {}, ofm channels = {}".format(
Tim Hall79d07d22020-04-27 18:20:16 +0100427 op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3]
428 )
429 )
Tim Hall79d07d22020-04-27 18:20:16 +0100430 return op
431
432
433# Reorder activation op if it's after the memory only operations
434def fixup_act_reorder(op, arch):
435 if op.type in activation_ops:
436 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100437 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100438 act_op = op.clone("_reordered")
439 act_op.inputs = [prep_op.inputs[0]]
440 act_op_out = act_op.inputs[0].clone("_acted")
441 act_op_out.quantization = op.outputs[0].quantization.clone()
442 act_op_out.ops = [act_op]
443 act_op.outputs = [act_op_out]
444 prep_op.inputs[0] = act_op_out
445 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
446
447 # Mark the op so that it will be removed as passthrough later on
448 op.type = "Identity"
449 return op
450
Charles Xu78792222020-05-13 10:15:26 +0200451def fixup_elementwise_with_scalars(op, arch):
452 if op.type in binary_elementwise_op:
453 ifm_tensor, ifm2_tensor, _, ofm_tensor = op.get_ifm_ifm2_weights_ofm()
454 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
455 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
456 if diff > 0:
457 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
458 elif diff < 0:
459 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
460 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100461
Tim Hall4e127762020-05-15 16:05:49 +0100462# Set input/output tensor equivalence to the same id for memory operations
463def set_tensor_equivalence(op, arch):
464 if op.type == "Reshape":
465 eid = op.outputs[0].equivalence_id
466 for inp in op.inputs:
467 inp.equivalence_id = eid
468 return op
469
470
Tim Hall79d07d22020-04-27 18:20:16 +0100471def convert_mul_max_to_abs_or_lrelu(op, arch):
Diego Russoea6111a2020-04-14 18:41:58 +0100472 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100473
474 Input X For X = -1 or X > 0
475 | \ / This subgraph can be replaced with either
476 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
477 | /
478 Max
479 """
480
481 if op.type == "Maximum":
482 # finds the Mul input(s) to the Max
483 muls = [i for i in op.inputs if i.ops[0].type == "MulAct"]
484 if len(muls) == 1:
485 mul = muls[0].ops[0]
486 elif len(muls) == 2:
487 # In the case both inputs are Muls, find the one with the same input as the Max
488 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
489 else:
490 # No Mul inputs
491 return op
492
493 # make sure the Mul doesn't have any other consumers
494 if len(mul.outputs[0].consumers()) != 1:
495 return op
496 # make sure the Mul doesn't have a faf
497 if mul.attrs["fused_activation_function"]:
498 return op
499
500 # finds the branched input that goes to both the Max and the Mul
501 shared = set(op.inputs) & set(mul.inputs)
502 if len(shared) == 1:
503 shared_in = shared.pop()
504 # find the constant scalar input to the Mul
505 const_tens = (set(mul.inputs) - {shared_in}).pop()
506 # check that it is a scalar
507 if const_tens.shape != []:
508 return op
509 const = const_tens.ops[0]
510 # check that it is a constant
511 if const.type != "Const":
512 return op
513 else:
514 return op
515
516 val = const.outputs[0].values
517 if val >= 0:
518 new_op = "LeakyRelu"
519 op.attrs["alpha"] = val
520 elif val == -1:
521 new_op = "Abs"
522 else:
523 return op
524
525 op.type = op.type.replace("Maximum", new_op)
526 op.name = op.name.replace("Maximum", new_op)
527 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op)
528 op.inputs = [shared_in]
529 return op
530
531
Dwight Lidman42fed942020-05-29 09:37:03 +0200532def add_attrs_to_resizebilinear(op, arch):
533 if op.type == 'ResizeBilinear' and op.run_on_npu:
534 input_tensor = op.inputs[0]
535 upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2]
536 out_shape = op.outputs[0].shape[1:3]
537 if not op.attrs["align_corners"] and out_shape == upscaled_shape:
538 # this means the output is supposed to be a x2 upscale,
539 # so we need to do SAME padding
540 op.attrs["padding"] = b"SAME"
541 elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]:
542 # here we can just run the avg pool without padding and
543 # produce a (M * 2 - 1, N * 2 - 1) sized output
544 op.attrs["padding"] = b"VALID"
545 else:
546 # If this exception is raised, something is wrong with the supported op check
547 raise UnsupportedFeatureError("Unsupported upscaling factor")
548 input_tensor.resampling_mode = resampling_mode.NEAREST
549 op.attrs.update({
550 'strides': (1, 1, 1, 1),
551 'ksize': (1, 2, 2, 1),
552 })
553 return op
554
555
Tim Hall79d07d22020-04-27 18:20:16 +0100556def supported_operator_check(op, arch):
557 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
558 return op
559
560
561def optimise_graph_a(nng, arch, verbose_graph=False):
562 if verbose_graph:
563 nng.print_graph()
564
565 op_rewrite_list = [
566 # mark block type and check if the operations are supported
567 mark_npu_block_type,
Tim Hall4e127762020-05-15 16:05:49 +0100568 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +0100569 supported_operator_check,
570 # then do any rewrites of supported operators
571 convert_depthwise_to_conv,
572 fixup_fully_connected_input,
573 fixup_pack_input,
574 fixup_conv2d_backprop,
575 fixup_act_reorder,
Dwight Lidman42fed942020-05-29 09:37:03 +0200576 add_attrs_to_resizebilinear,
Tim Hall79d07d22020-04-27 18:20:16 +0100577 add_padding_fields,
578 mark_npu_block_type,
Charles Xu78792222020-05-13 10:15:26 +0200579 fixup_elementwise_with_scalars,
Tim Hall79d07d22020-04-27 18:20:16 +0100580 # convert_mul_max_to_abs_or_lrelu # TODO: enable optimisation once quantisation issues are resolved
581 ]
582
583 for idx, sg in enumerate(nng.subgraphs):
584 # rewrite graph pass
585 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Diego Russoea6111a2020-04-14 18:41:58 +0100586 sg, arch, [fixup_unpack_output], op_rewrite_list, rewrite_unsupported=False
Tim Hall79d07d22020-04-27 18:20:16 +0100587 )
588
589 for idx, sg in enumerate(nng.subgraphs):
590 # remove passthrough tensors
Diego Russoea6111a2020-04-14 18:41:58 +0100591 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [remove_passthrough_tensor], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100592
593 if verbose_graph:
594 nng.print_graph()
595 return nng
596
Diego Russoea6111a2020-04-14 18:41:58 +0100597
Tim Hall79d07d22020-04-27 18:20:16 +0100598def optimise_graph_b(nng, arch, verbose_graph=False):
599 if verbose_graph:
600 nng.print_graph()
601
602 for idx, sg in enumerate(nng.subgraphs):
603 # combined rewrite graph pass
Diego Russoea6111a2020-04-14 18:41:58 +0100604 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [rewrite_concat, rewrite_split], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100605
606 if verbose_graph:
607 nng.print_graph()
608 return nng