blob: dbf2b7b95c9c135c9672e5cbde5c45b8efc15cf1 [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
Louis Verhaarde0ef2732020-06-03 08:56:44 +020027from .numeric_util import full_shape
Diego Russoe8a10452020-04-21 17:39:10 +010028from .operation import NpuBlockType
29from .operation import Operation
30from .tensor import Tensor
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
Tim Hallc30f4952020-06-15 20:47:35 +0100134
Jacob Bohlincf7da102020-05-20 09:03:40 +0200135def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_dims):
136 upscaled_shape = [input_dims[0], input_dims[1] * stride[1], input_dims[2] * stride[2], input_dims[3]]
137 ypad = needed_total_padding(int(upscaled_shape[1]), int(stride[1]), int(kernel_size[0]))
138 xpad = needed_total_padding(int(upscaled_shape[2]), int(stride[2]), int(kernel_size[1]))
139
140 if padding_type == b"SAME":
141 right_pad = ((xpad + 1) // 2) - 1
142 bottom_pad = ((ypad + 1) // 2) - 1
143 left_pad = max(kernel_size[0] - 1 - right_pad, 0)
144 top_pad = max(kernel_size[1] - 1 - bottom_pad, 0)
145 elif padding_type == b"VALID":
146 right_pad = (xpad + 1) // 2
147 bottom_pad = (ypad + 1) // 2
148 left_pad = max(kernel_size[0] - right_pad, 0)
149 top_pad = max(kernel_size[1] - bottom_pad, 0)
150 else:
151 assert 0, "Unknown padding"
152
153 padding = (top_pad, left_pad, bottom_pad, right_pad)
154 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
155 return padding, skirt
156
Tim Hall79d07d22020-04-27 18:20:16 +0100157
158def fixup_conv2d_backprop(op, arch):
159 if op.type == "Conv2DBackpropInput":
160 # flip the inputs
161 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200162 op.type = "Conv2DBackpropInputSwitchedBias"
163 weight_shape = op.inputs[1].shape
164 weight_sets = weight_shape[3]
165
166 if len(op.inputs) < 4:
167 # Add bias/scale tensor filled with zeros
168 scale_op = Operation("Const", op.name + "_bias")
169 scale_tens = Tensor([weight_sets], DataType.int32, op.name + "_bias_tens")
170 scale_tens.values = [0] * weight_sets
171 scale_tens.quant_values = [0] * weight_sets
172 scale_tens.ops = [scale_op]
173 scale_op.outputs = [scale_tens]
174 scale_tens.consumer_list = [op]
175 op.inputs.append(scale_tens)
176
177 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100178 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100179
180 return op
181
182
183def fixup_fully_connected_input(op, arch):
184 if op.type == "FullyConnectedAct":
185 inp = op.inputs[0]
186 weights = op.inputs[1]
187
188 n_in_elems = weights.shape[-2]
189 elms = inp.elements()
190 batch_size = elms // n_in_elems
191 assert batch_size * n_in_elems == elms
192
193 desired_shape = [batch_size, n_in_elems]
194 if inp.shape != desired_shape:
195 # mismatch, insert a reshape to fix this.
196 reshape_name = op.name + "_reshape"
197 new_shape_tens = Tensor([1], DataType.int32, reshape_name + "_shape")
198 new_shape_tens.values = np.array(desired_shape)
199 new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const")
200 new_shape_tens.ops = [new_shape_tens_const]
201 new_shape_tens_const.outputs = [new_shape_tens]
202
203 reshape_op = Operation("Reshape", reshape_name)
204 reshape_op.inputs = [inp, new_shape_tens]
205 reshape_op.attrs["new_shape"] = desired_shape
206 reshape_out = inp.clone("_reshaped")
207 reshape_out.shape = reshape_out.storage_shape = reshape_out.bandwidth_shape = desired_shape
208 reshape_out.ops = [reshape_op]
209 reshape_op.outputs = [reshape_out]
210
211 op.inputs[0] = reshape_out
212
213 return op
214
215
216def fixup_pack_input(op, arch):
217 if op.type == "Pack":
218 # Pack is also referred to as Stack
219 # Requires the rewrite_concat function to be called on the op afterwards
220 axis = int(op.attrs["axis"])
221 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
222
223 # Construct 1 shape tensor to be used by all inserted reshape ops
224 new_shape_name = op.name + "_reshape_shape"
225 new_shape_tens = Tensor([1], DataType.int32, new_shape_name)
226 new_shape_tens.values = np.array(desired_shape)
227 new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const")
228 new_shape_tens.ops = [new_shape_tens_const]
229 new_shape_tens_const.outputs = [new_shape_tens]
230
231 for idx, inp in enumerate(op.inputs):
232 reshape_name = op.name + str(idx) + "_reshape"
233 reshape_op = Operation("Reshape", reshape_name)
234 reshape_op.inputs = [inp, new_shape_tens]
235 reshape_op.attrs["new_shape"] = desired_shape
236 reshape_out = inp.clone("_reshaped")
237 reshape_out.shape = reshape_out.storage_shape = reshape_out.bandwidth_shape = desired_shape
238 reshape_out.ops = [reshape_op]
239 reshape_op.outputs = [reshape_out]
240
241 op.inputs[idx] = reshape_out
242
243 op.type = "PackReshaped"
244
245 return op
246
247
248def fixup_unpack_output(tens, arch):
249 op = tens.ops[0]
250 if op.type in set(("Unpack", "StridedSlice")):
251 # Unpack is also referred to as Unstack
252 # Requires the rewrite_split function to be called on the op afterwards
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200253
254 reshape_input_shape = tens.shape
Tim Hall79d07d22020-04-27 18:20:16 +0100255 if op.type == "StridedSlice":
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200256 new_axis_mask = op.attrs["new_axis_mask"]
Tim Hall79d07d22020-04-27 18:20:16 +0100257 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Louis Verhaard7db78962020-05-25 15:05:26 +0200258 ellipsis_mask = op.attrs["ellipsis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200259
260 if (new_axis_mask != 0 and shrink_axis_mask != 0) or ellipsis_mask != 0:
261 # Not supported, will be put on CPU
262 return tens
263 if shrink_axis_mask == 0 and new_axis_mask == 0:
Tim Hall79d07d22020-04-27 18:20:16 +0100264 # Equal Rank StridedSlice, no need to insert reshape
265 return tens
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200266 elif shrink_axis_mask != 0:
267 n = 0
268 axis = 0
269 while shrink_axis_mask:
270 prev_mask = shrink_axis_mask
271 n += 1
272 shrink_axis_mask &= shrink_axis_mask - 1
273 axis = int(math.log2(prev_mask - shrink_axis_mask))
274 reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100275
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200276 assert len(tens.shape) == (len(op.inputs[0].shape) - n)
277 op.attrs["shrink_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100278
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200279 elif new_axis_mask != 0:
280 n = 0
281 axis = 0
282 while new_axis_mask:
283 prev_mask = new_axis_mask
284 n += 1
285 new_axis_mask &= new_axis_mask - 1
286 axis = int(math.log2(prev_mask - new_axis_mask))
Louis Verhaard7db78962020-05-25 15:05:26 +0200287 reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1) :]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200288 new_axis_mask >>= 1
289
290 assert len(tens.shape) == (len(op.inputs[0].shape) + n)
291 op.attrs["new_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100292 else:
293 axis = int(op.attrs["axis"])
294 op.type = "UnpackReshaped"
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200295 reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100296
297 # Construct 1 shape tensor to be used by all inserted reshape ops
298 new_shape_name = op.name + "_reshape_shape"
299 new_shape_tens = Tensor([1], DataType.int32, new_shape_name)
300 new_shape_tens.values = np.array(tens.shape)
301 new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const")
302 new_shape_tens.ops = [new_shape_tens_const]
303 new_shape_tens_const.outputs = [new_shape_tens]
304
305 for idx, out_tens in enumerate(op.outputs):
306 reshape_name = op.name + str(idx) + "_reshape"
307 reshape_op = Operation("Reshape", reshape_name)
308 reshape_op.outputs = [out_tens]
309 reshape_in = out_tens.clone("_reshaped")
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200310 reshape_in.shape = reshape_in.storage_shape = reshape_in.bandwidth_shape = reshape_input_shape
Tim Hall79d07d22020-04-27 18:20:16 +0100311 reshape_in.ops = [op]
312 out_tens.ops = [reshape_op]
313 reshape_op.inputs = [reshape_in, new_shape_tens]
314
315 op.outputs[idx] = reshape_in
316
317 return tens
318
319
320def add_padding_fields(op, arch):
321 if "padding" in op.attrs:
322 if "Conv" in op.type:
323 kernel_size = op.inputs[1].shape[:2]
324 input_shape = op.inputs[0].shape
Dwight Lidman3ec04ac2020-04-30 11:54:48 +0200325 elif "Pool" in op.type or "ResizeBilinear" == op.type:
Tim Hall79d07d22020-04-27 18:20:16 +0100326 kernel_size = op.attrs["ksize"][1:3]
327 input_shape = op.inputs[0].shape
328 elif op.type == "ExtractImagePatches":
329 kernel_size = op.attrs["ksizes"][1:3]
330 input_shape = op.inputs[0].shape
331 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200332 raise UnsupportedFeatureError("Unknown operation that uses padding: {}".format(op.type))
Tim Hall79d07d22020-04-27 18:20:16 +0100333
Jacob Bohlincf7da102020-05-20 09:03:40 +0200334 if op.type == "Conv2DBackpropInputSwitchedBias":
Tim Hallc30f4952020-06-15 20:47:35 +0100335 padding, skirt = calc_upscaled_padding_and_skirt(
336 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape
337 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200338 else:
339 dilation_h, dilation_w = op.get_dilation_h_w()
340 dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1]
Tim Hallc30f4952020-06-15 20:47:35 +0100341 padding, skirt = calc_padding_and_skirt(
342 op.attrs["padding"], dilated_kernel_size, op.attrs["strides"], input_shape
343 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200344
Tim Hall79d07d22020-04-27 18:20:16 +0100345 op.attrs["explicit_padding"] = padding
346 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200347
Tim Hall79d07d22020-04-27 18:20:16 +0100348 return op
349
350
Jacob Bohlincf7da102020-05-20 09:03:40 +0200351conv_op = set(("Conv2D", "QuantizedConv2D", "Conv2DBackpropInputSwitchedBias", "Conv2DBiasAct"))
Tim Hall79d07d22020-04-27 18:20:16 +0100352fc_op = set(
353 (
354 "MatMul",
355 "QuantizedMatMul",
356 "BlockLSTM",
357 "RnnAct",
358 "UnidirectionalSequenceRnnAct",
359 "BidirectionalSequenceRnnAct",
360 "LstmAct",
361 "UnidirectionalSequenceLstmAct",
362 "BidirectionalSequenceLstmAct",
363 "FullyConnectedAct",
364 )
365)
366depthwise_op = set(("DepthwiseConv2dNative", "DepthwiseConv2dBiasAct",))
Louis Verhaard7db78962020-05-25 15:05:26 +0200367pool_op = set(
368 ("AvgPool", "MaxPool", "QuantizedAvgPool", "QuantizedMaxPool", "AvgPoolAct", "MaxPoolAct", "ResizeBilinear",)
369)
Tim Hall79d07d22020-04-27 18:20:16 +0100370elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum", "LeakyRelu", "Abs"))
Charles Xu78792222020-05-13 10:15:26 +0200371binary_elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum"))
Tim Hall79d07d22020-04-27 18:20:16 +0100372activation_ops = set(("Relu", "Relu6", "ReluN1To1", "Sigmoid", "Tanh"))
373memory_only_ops = set(("Reshape",))
374
Diego Russoea6111a2020-04-14 18:41:58 +0100375
Tim Hall79d07d22020-04-27 18:20:16 +0100376# Check if the op can be reordered
377def get_prepend_op(op):
378 inp = op.inputs[0]
379 # The op should be reordered between prev_op and prep_op
380 prev_op = inp.ops[-1]
381 prep_op = None
382 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
383 prep_op = prev_op
384 inp = prev_op.inputs[0]
385 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100386 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 +0100387 return prep_op
388
389 return None
390
391
392def mark_npu_block_type(op, arch):
393 npu_block_type = NpuBlockType.Default
394 if op.type in conv_op:
395 npu_block_type = NpuBlockType.ConvolutionMxN
396 elif op.type in fc_op:
397 npu_block_type = NpuBlockType.VectorProduct
398 elif op.type in depthwise_op:
399 npu_block_type = NpuBlockType.ConvolutionDepthWise
400 elif op.type in pool_op:
401 npu_block_type = NpuBlockType.Pooling
402 elif op.type in elementwise_op:
403 npu_block_type = NpuBlockType.ElementWise
404
405 op.attrs["npu_block_type"] = npu_block_type
406 return op
407
408
409def convert_depthwise_to_conv(op, arch):
410 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
411 # the ofm depth equals the depth multipler.
412 # If those conditions are true, then we can perform a simple
413 # switch of the operator type (and weight order)
414
415 if ("DepthwiseConv2d" in op.type) and (op.attrs["depth_multiplier"] != 1):
416 ifm_tensor = op.inputs[0]
417 weight_tensor = op.inputs[1]
418 ofm_tensor = op.outputs[0]
419 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
420 # Change op type to Conv2d
421 op.type = op.type.replace("DepthwiseConv2d", "Conv2D")
422 del op.attrs["channel_multiplier"]
423 del op.attrs["depth_multiplier"]
424
425 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
426 weight_tensor.shape = weight_tensor.storage_shape = weight_tensor.bandwidth_shape = list(
427 weight_tensor.quant_values.shape
428 )
429 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200430 raise UnsupportedFeatureError(
431 "Unsupported DepthwiseConv2d with depth_multiplier = {}, ifm channels = {}, ofm channels = {}".format(
Tim Hall79d07d22020-04-27 18:20:16 +0100432 op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3]
433 )
434 )
Tim Hall79d07d22020-04-27 18:20:16 +0100435 return op
436
437
Jacob Bohline843d332020-06-23 12:12:56 +0200438def reorder_depthwise_weights(op, arch):
439 if "DepthwiseConv2d" in op.type:
440 weight_tensor = op.inputs[1]
441 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
442 weight_tensor.shape = weight_tensor.storage_shape = weight_tensor.bandwidth_shape = list(
443 weight_tensor.quant_values.shape
444 )
445 weight_tensor.weight_transpose_depthwise = True
446
447 return op
448
449
Tim Hall79d07d22020-04-27 18:20:16 +0100450# Reorder activation op if it's after the memory only operations
451def fixup_act_reorder(op, arch):
452 if op.type in activation_ops:
453 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100454 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100455 act_op = op.clone("_reordered")
456 act_op.inputs = [prep_op.inputs[0]]
457 act_op_out = act_op.inputs[0].clone("_acted")
458 act_op_out.quantization = op.outputs[0].quantization.clone()
459 act_op_out.ops = [act_op]
460 act_op.outputs = [act_op_out]
461 prep_op.inputs[0] = act_op_out
462 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
463
464 # Mark the op so that it will be removed as passthrough later on
465 op.type = "Identity"
466 return op
467
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200468
Charles Xu78792222020-05-13 10:15:26 +0200469def fixup_elementwise_with_scalars(op, arch):
470 if op.type in binary_elementwise_op:
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200471 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200472 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
473 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
474 if diff > 0:
475 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
476 elif diff < 0:
477 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200478 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
479 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
480 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
481 ifm_tensor.storage_shape = ifm_tensor.shape
482 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
483 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
484 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
485 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200486 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100487
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200488
Tim Hall4e127762020-05-15 16:05:49 +0100489# Set input/output tensor equivalence to the same id for memory operations
490def set_tensor_equivalence(op, arch):
491 if op.type == "Reshape":
492 eid = op.outputs[0].equivalence_id
493 for inp in op.inputs:
494 inp.equivalence_id = eid
495 return op
496
497
Tim Hall79d07d22020-04-27 18:20:16 +0100498def convert_mul_max_to_abs_or_lrelu(op, arch):
Diego Russoea6111a2020-04-14 18:41:58 +0100499 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100500
501 Input X For X = -1 or X > 0
502 | \ / This subgraph can be replaced with either
503 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
504 | /
505 Max
506 """
507
508 if op.type == "Maximum":
509 # finds the Mul input(s) to the Max
510 muls = [i for i in op.inputs if i.ops[0].type == "MulAct"]
511 if len(muls) == 1:
512 mul = muls[0].ops[0]
513 elif len(muls) == 2:
514 # In the case both inputs are Muls, find the one with the same input as the Max
515 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
516 else:
517 # No Mul inputs
518 return op
519
520 # make sure the Mul doesn't have any other consumers
521 if len(mul.outputs[0].consumers()) != 1:
522 return op
523 # make sure the Mul doesn't have a faf
524 if mul.attrs["fused_activation_function"]:
525 return op
526
527 # finds the branched input that goes to both the Max and the Mul
528 shared = set(op.inputs) & set(mul.inputs)
529 if len(shared) == 1:
530 shared_in = shared.pop()
531 # find the constant scalar input to the Mul
532 const_tens = (set(mul.inputs) - {shared_in}).pop()
533 # check that it is a scalar
534 if const_tens.shape != []:
535 return op
536 const = const_tens.ops[0]
537 # check that it is a constant
538 if const.type != "Const":
539 return op
540 else:
541 return op
542
543 val = const.outputs[0].values
544 if val >= 0:
545 new_op = "LeakyRelu"
546 op.attrs["alpha"] = val
547 elif val == -1:
548 new_op = "Abs"
549 else:
550 return op
551
552 op.type = op.type.replace("Maximum", new_op)
553 op.name = op.name.replace("Maximum", new_op)
554 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op)
555 op.inputs = [shared_in]
556 return op
557
558
Dwight Lidman42fed942020-05-29 09:37:03 +0200559def add_attrs_to_resizebilinear(op, arch):
Tim Hallc30f4952020-06-15 20:47:35 +0100560 if op.type == "ResizeBilinear" and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +0200561 input_tensor = op.inputs[0]
562 upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2]
563 out_shape = op.outputs[0].shape[1:3]
564 if not op.attrs["align_corners"] and out_shape == upscaled_shape:
565 # this means the output is supposed to be a x2 upscale,
566 # so we need to do SAME padding
567 op.attrs["padding"] = b"SAME"
568 elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]:
569 # here we can just run the avg pool without padding and
570 # produce a (M * 2 - 1, N * 2 - 1) sized output
571 op.attrs["padding"] = b"VALID"
572 else:
573 # If this exception is raised, something is wrong with the supported op check
574 raise UnsupportedFeatureError("Unsupported upscaling factor")
575 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +0100576 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +0200577 return op
578
579
Tim Hall79d07d22020-04-27 18:20:16 +0100580def supported_operator_check(op, arch):
581 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
582 return op
583
584
585def optimise_graph_a(nng, arch, verbose_graph=False):
586 if verbose_graph:
587 nng.print_graph()
588
589 op_rewrite_list = [
590 # mark block type and check if the operations are supported
591 mark_npu_block_type,
Tim Hall4e127762020-05-15 16:05:49 +0100592 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +0100593 supported_operator_check,
594 # then do any rewrites of supported operators
595 convert_depthwise_to_conv,
596 fixup_fully_connected_input,
597 fixup_pack_input,
598 fixup_conv2d_backprop,
599 fixup_act_reorder,
Dwight Lidman42fed942020-05-29 09:37:03 +0200600 add_attrs_to_resizebilinear,
Tim Hall79d07d22020-04-27 18:20:16 +0100601 add_padding_fields,
602 mark_npu_block_type,
Charles Xu78792222020-05-13 10:15:26 +0200603 fixup_elementwise_with_scalars,
Jacob Bohline843d332020-06-23 12:12:56 +0200604 reorder_depthwise_weights,
Tim Hall79d07d22020-04-27 18:20:16 +0100605 # convert_mul_max_to_abs_or_lrelu # TODO: enable optimisation once quantisation issues are resolved
606 ]
607
608 for idx, sg in enumerate(nng.subgraphs):
609 # rewrite graph pass
610 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Diego Russoea6111a2020-04-14 18:41:58 +0100611 sg, arch, [fixup_unpack_output], op_rewrite_list, rewrite_unsupported=False
Tim Hall79d07d22020-04-27 18:20:16 +0100612 )
613
614 for idx, sg in enumerate(nng.subgraphs):
615 # remove passthrough tensors
Diego Russoea6111a2020-04-14 18:41:58 +0100616 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [remove_passthrough_tensor], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100617
618 if verbose_graph:
619 nng.print_graph()
620 return nng
621
Diego Russoea6111a2020-04-14 18:41:58 +0100622
Tim Hall79d07d22020-04-27 18:20:16 +0100623def optimise_graph_b(nng, arch, verbose_graph=False):
624 if verbose_graph:
625 nng.print_graph()
626
627 for idx, sg in enumerate(nng.subgraphs):
628 # combined rewrite graph pass
Diego Russoea6111a2020-04-14 18:41:58 +0100629 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [rewrite_concat, rewrite_split], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100630
631 if verbose_graph:
632 nng.print_graph()
633 return nng