blob: b2b233eb06bb959128ca5433de5afbfc6ac36e66 [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
Diego Russoe8a10452020-04-21 17:39:10 +010025from .operation import NpuBlockType
26from .operation import Operation
27from .tensor import Tensor
Tim Hall79d07d22020-04-27 18:20:16 +010028
29passthrough_nodes = set(("Identity",))
30
31
32def remove_passthrough_tensor(tens, arch):
33 if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes:
34 assert len(tens.ops[0].inputs) == 1
35 tens = tens.ops[0].inputs[0]
36 return tens
37
38
39def rewrite_concat(tens, arch):
40 if len(tens.ops) == 1 and tens.ops[0].is_concat_op():
41 concat_op = tens.ops[0]
42 if tens != concat_op.outputs[0]:
43 return tens # don't attempt to rewrite the min/max outputs of QuantizedConcat
44
45 # Not supported so leave it and run on CPU
46 if not concat_op.run_on_npu:
47 return tens
48
49 inputs, axis = concat_op.get_concat_inputs_axis()
50
51 tens.ops = []
52 offset = 0
53 for idx, inp in enumerate(inputs):
54 new_op = Operation("ConcatSliceWrite", concat_op.name + str(idx))
55 new_op.inputs = [inp]
56 new_op.outputs = [tens]
57 new_op.attrs["concat_axis"] = axis
58 new_op.attrs["concat_start"] = offset
59 offset += inp.shape[axis]
60 new_op.attrs["concat_end"] = offset
61 new_op.run_on_npu = True
62 tens.ops.append(new_op)
63 assert tens.shape[axis] == offset
64
65 return tens
66
67
68def rewrite_split(tens, arch):
69
70 if len(tens.ops) == 1 and tens.ops[0].is_split_op():
71 split_op = tens.ops[0]
72
73 # Not supported so leave it and run on CPU
74 if not split_op.run_on_npu:
75 return tens
76
77 inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis()
78
79 tens.ops = []
80 new_op = Operation("SplitSliceRead", split_op.name)
81 new_op.inputs = [inp]
82 new_op.outputs = [tens]
83
84 # For Split the offset cannot be extracted from the tensor so it has to
85 # be calculated from the index of the output tensor
Diego Russoea6111a2020-04-14 18:41:58 +010086 if axis is not None:
Tim Hall79d07d22020-04-27 18:20:16 +010087 # Get the start and end of the split
88 offset_start = [0] * len(tens.shape)
89 offset_end = [0] * len(tens.shape)
90 for out in outputs:
91 if out == tens:
92 break
93 offset_start[axis] += out.shape[axis]
94
95 offset_end[axis] = offset_start[axis] + tens.shape[axis]
96
97 new_op.attrs["split_start"] = offset_start
98 new_op.attrs["split_end"] = offset_end
99 new_op.run_on_npu = True
100 tens.ops.append(new_op)
101
102 return tens
103
104
105def needed_total_padding(input_size, stride, filter_size):
106 out_size = (input_size + stride - 1) // stride
107 needed_input = (out_size - 1) * stride + filter_size
108 total_padding = max(0, needed_input - input_size)
109 return total_padding
110
111
112def calc_padding_and_skirt(padding_type, kernel_size, stride, input_dims):
113 ypad = needed_total_padding(int(input_dims[1]), int(stride[1]), int(kernel_size[0]))
114 xpad = needed_total_padding(int(input_dims[2]), int(stride[2]), int(kernel_size[1]))
115 if padding_type == b"SAME":
116 left_pad = (xpad + 0) // 2
117 right_pad = (xpad + 1) // 2
118 top_pad = (ypad + 0) // 2
119 bottom_pad = (ypad + 1) // 2
120 elif padding_type == b"VALID":
121 left_pad = 0
122 right_pad = 0
123 top_pad = 0
124 bottom_pad = 0
125 else:
126 assert 0, "Unknown padding"
127 padding = (top_pad, left_pad, bottom_pad, right_pad)
128 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
129 return padding, skirt
130
131
132def fixup_conv2d_backprop(op, arch):
133 if op.type == "Conv2DBackpropInput":
134 # flip the inputs
135 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
136 op.type = "Conv2DBackpropInputSwitched"
137
138 return op
139
140
141def fixup_fully_connected_input(op, arch):
142 if op.type == "FullyConnectedAct":
143 inp = op.inputs[0]
144 weights = op.inputs[1]
145
146 n_in_elems = weights.shape[-2]
147 elms = inp.elements()
148 batch_size = elms // n_in_elems
149 assert batch_size * n_in_elems == elms
150
151 desired_shape = [batch_size, n_in_elems]
152 if inp.shape != desired_shape:
153 # mismatch, insert a reshape to fix this.
154 reshape_name = op.name + "_reshape"
155 new_shape_tens = Tensor([1], DataType.int32, reshape_name + "_shape")
156 new_shape_tens.values = np.array(desired_shape)
157 new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const")
158 new_shape_tens.ops = [new_shape_tens_const]
159 new_shape_tens_const.outputs = [new_shape_tens]
160
161 reshape_op = Operation("Reshape", reshape_name)
162 reshape_op.inputs = [inp, new_shape_tens]
163 reshape_op.attrs["new_shape"] = desired_shape
164 reshape_out = inp.clone("_reshaped")
165 reshape_out.shape = reshape_out.storage_shape = reshape_out.bandwidth_shape = desired_shape
166 reshape_out.ops = [reshape_op]
167 reshape_op.outputs = [reshape_out]
168
169 op.inputs[0] = reshape_out
170
171 return op
172
173
174def fixup_pack_input(op, arch):
175 if op.type == "Pack":
176 # Pack is also referred to as Stack
177 # Requires the rewrite_concat function to be called on the op afterwards
178 axis = int(op.attrs["axis"])
179 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
180
181 # Construct 1 shape tensor to be used by all inserted reshape ops
182 new_shape_name = op.name + "_reshape_shape"
183 new_shape_tens = Tensor([1], DataType.int32, new_shape_name)
184 new_shape_tens.values = np.array(desired_shape)
185 new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const")
186 new_shape_tens.ops = [new_shape_tens_const]
187 new_shape_tens_const.outputs = [new_shape_tens]
188
189 for idx, inp in enumerate(op.inputs):
190 reshape_name = op.name + str(idx) + "_reshape"
191 reshape_op = Operation("Reshape", reshape_name)
192 reshape_op.inputs = [inp, new_shape_tens]
193 reshape_op.attrs["new_shape"] = desired_shape
194 reshape_out = inp.clone("_reshaped")
195 reshape_out.shape = reshape_out.storage_shape = reshape_out.bandwidth_shape = desired_shape
196 reshape_out.ops = [reshape_op]
197 reshape_op.outputs = [reshape_out]
198
199 op.inputs[idx] = reshape_out
200
201 op.type = "PackReshaped"
202
203 return op
204
205
206def fixup_unpack_output(tens, arch):
207 op = tens.ops[0]
208 if op.type in set(("Unpack", "StridedSlice")):
209 # Unpack is also referred to as Unstack
210 # Requires the rewrite_split function to be called on the op afterwards
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200211
212 reshape_input_shape = tens.shape
Tim Hall79d07d22020-04-27 18:20:16 +0100213 if op.type == "StridedSlice":
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200214 new_axis_mask = op.attrs["new_axis_mask"]
Tim Hall79d07d22020-04-27 18:20:16 +0100215 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200216 ellipsis_mask = op.attrs["ellipsis_mask"]
217
218 if (new_axis_mask != 0 and shrink_axis_mask != 0) or ellipsis_mask != 0:
219 # Not supported, will be put on CPU
220 return tens
221 if shrink_axis_mask == 0 and new_axis_mask == 0:
Tim Hall79d07d22020-04-27 18:20:16 +0100222 # Equal Rank StridedSlice, no need to insert reshape
223 return tens
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200224 elif shrink_axis_mask != 0:
225 n = 0
226 axis = 0
227 while shrink_axis_mask:
228 prev_mask = shrink_axis_mask
229 n += 1
230 shrink_axis_mask &= shrink_axis_mask - 1
231 axis = int(math.log2(prev_mask - shrink_axis_mask))
232 reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100233
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200234 assert len(tens.shape) == (len(op.inputs[0].shape) - n)
235 op.attrs["shrink_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100236
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200237 elif new_axis_mask != 0:
238 n = 0
239 axis = 0
240 while new_axis_mask:
241 prev_mask = new_axis_mask
242 n += 1
243 new_axis_mask &= new_axis_mask - 1
244 axis = int(math.log2(prev_mask - new_axis_mask))
245 reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1):]
246 new_axis_mask >>= 1
247
248 assert len(tens.shape) == (len(op.inputs[0].shape) + n)
249 op.attrs["new_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100250 else:
251 axis = int(op.attrs["axis"])
252 op.type = "UnpackReshaped"
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200253 reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100254
255 # Construct 1 shape tensor to be used by all inserted reshape ops
256 new_shape_name = op.name + "_reshape_shape"
257 new_shape_tens = Tensor([1], DataType.int32, new_shape_name)
258 new_shape_tens.values = np.array(tens.shape)
259 new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const")
260 new_shape_tens.ops = [new_shape_tens_const]
261 new_shape_tens_const.outputs = [new_shape_tens]
262
263 for idx, out_tens in enumerate(op.outputs):
264 reshape_name = op.name + str(idx) + "_reshape"
265 reshape_op = Operation("Reshape", reshape_name)
266 reshape_op.outputs = [out_tens]
267 reshape_in = out_tens.clone("_reshaped")
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200268 reshape_in.shape = reshape_in.storage_shape = reshape_in.bandwidth_shape = reshape_input_shape
Tim Hall79d07d22020-04-27 18:20:16 +0100269 reshape_in.ops = [op]
270 out_tens.ops = [reshape_op]
271 reshape_op.inputs = [reshape_in, new_shape_tens]
272
273 op.outputs[idx] = reshape_in
274
275 return tens
276
277
278def add_padding_fields(op, arch):
279 if "padding" in op.attrs:
280 if "Conv" in op.type:
281 kernel_size = op.inputs[1].shape[:2]
282 input_shape = op.inputs[0].shape
Dwight Lidman3ec04ac2020-04-30 11:54:48 +0200283 elif "Pool" in op.type or "ResizeBilinear" == op.type:
Tim Hall79d07d22020-04-27 18:20:16 +0100284 kernel_size = op.attrs["ksize"][1:3]
285 input_shape = op.inputs[0].shape
286 elif op.type == "ExtractImagePatches":
287 kernel_size = op.attrs["ksizes"][1:3]
288 input_shape = op.inputs[0].shape
289 else:
290 assert 0, "Unknown operation that uses padding"
291
292 padding, skirt = calc_padding_and_skirt(op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape)
293 op.attrs["explicit_padding"] = padding
294 op.attrs["skirt"] = skirt
295 return op
296
297
298conv_op = set(("Conv2D", "QuantizedConv2D", "Conv2DBackpropInputSwitched", "Conv2DBiasAct"))
299fc_op = set(
300 (
301 "MatMul",
302 "QuantizedMatMul",
303 "BlockLSTM",
304 "RnnAct",
305 "UnidirectionalSequenceRnnAct",
306 "BidirectionalSequenceRnnAct",
307 "LstmAct",
308 "UnidirectionalSequenceLstmAct",
309 "BidirectionalSequenceLstmAct",
310 "FullyConnectedAct",
311 )
312)
313depthwise_op = set(("DepthwiseConv2dNative", "DepthwiseConv2dBiasAct",))
Dwight Lidman3ec04ac2020-04-30 11:54:48 +0200314pool_op = set(("AvgPool", "MaxPool", "QuantizedAvgPool", "QuantizedMaxPool", "AvgPoolAct", "MaxPoolAct", "ResizeBilinear",))
Tim Hall79d07d22020-04-27 18:20:16 +0100315elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum", "LeakyRelu", "Abs"))
316activation_ops = set(("Relu", "Relu6", "ReluN1To1", "Sigmoid", "Tanh"))
317memory_only_ops = set(("Reshape",))
318
Diego Russoea6111a2020-04-14 18:41:58 +0100319
Tim Hall79d07d22020-04-27 18:20:16 +0100320# Check if the op can be reordered
321def get_prepend_op(op):
322 inp = op.inputs[0]
323 # The op should be reordered between prev_op and prep_op
324 prev_op = inp.ops[-1]
325 prep_op = None
326 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
327 prep_op = prev_op
328 inp = prev_op.inputs[0]
329 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100330 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 +0100331 return prep_op
332
333 return None
334
335
336def mark_npu_block_type(op, arch):
337 npu_block_type = NpuBlockType.Default
338 if op.type in conv_op:
339 npu_block_type = NpuBlockType.ConvolutionMxN
340 elif op.type in fc_op:
341 npu_block_type = NpuBlockType.VectorProduct
342 elif op.type in depthwise_op:
343 npu_block_type = NpuBlockType.ConvolutionDepthWise
344 elif op.type in pool_op:
345 npu_block_type = NpuBlockType.Pooling
346 elif op.type in elementwise_op:
347 npu_block_type = NpuBlockType.ElementWise
348
349 op.attrs["npu_block_type"] = npu_block_type
350 return op
351
352
353def convert_depthwise_to_conv(op, arch):
354 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
355 # the ofm depth equals the depth multipler.
356 # If those conditions are true, then we can perform a simple
357 # switch of the operator type (and weight order)
358
359 if ("DepthwiseConv2d" in op.type) and (op.attrs["depth_multiplier"] != 1):
360 ifm_tensor = op.inputs[0]
361 weight_tensor = op.inputs[1]
362 ofm_tensor = op.outputs[0]
363 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
364 # Change op type to Conv2d
365 op.type = op.type.replace("DepthwiseConv2d", "Conv2D")
366 del op.attrs["channel_multiplier"]
367 del op.attrs["depth_multiplier"]
368
369 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
370 weight_tensor.shape = weight_tensor.storage_shape = weight_tensor.bandwidth_shape = list(
371 weight_tensor.quant_values.shape
372 )
373 else:
374 print(
375 "Error: Unsupported DepthwiseConv2d with depth_multiplier = {0}, "
376 "ifm channels = {1}, ofm channels = {2}".format(
377 op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3]
378 )
379 )
380 assert False
381 return op
382
383
384# Reorder activation op if it's after the memory only operations
385def fixup_act_reorder(op, arch):
386 if op.type in activation_ops:
387 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100388 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100389 act_op = op.clone("_reordered")
390 act_op.inputs = [prep_op.inputs[0]]
391 act_op_out = act_op.inputs[0].clone("_acted")
392 act_op_out.quantization = op.outputs[0].quantization.clone()
393 act_op_out.ops = [act_op]
394 act_op.outputs = [act_op_out]
395 prep_op.inputs[0] = act_op_out
396 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
397
398 # Mark the op so that it will be removed as passthrough later on
399 op.type = "Identity"
400 return op
401
402
403def convert_mul_max_to_abs_or_lrelu(op, arch):
Diego Russoea6111a2020-04-14 18:41:58 +0100404 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100405
406 Input X For X = -1 or X > 0
407 | \ / This subgraph can be replaced with either
408 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
409 | /
410 Max
411 """
412
413 if op.type == "Maximum":
414 # finds the Mul input(s) to the Max
415 muls = [i for i in op.inputs if i.ops[0].type == "MulAct"]
416 if len(muls) == 1:
417 mul = muls[0].ops[0]
418 elif len(muls) == 2:
419 # In the case both inputs are Muls, find the one with the same input as the Max
420 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
421 else:
422 # No Mul inputs
423 return op
424
425 # make sure the Mul doesn't have any other consumers
426 if len(mul.outputs[0].consumers()) != 1:
427 return op
428 # make sure the Mul doesn't have a faf
429 if mul.attrs["fused_activation_function"]:
430 return op
431
432 # finds the branched input that goes to both the Max and the Mul
433 shared = set(op.inputs) & set(mul.inputs)
434 if len(shared) == 1:
435 shared_in = shared.pop()
436 # find the constant scalar input to the Mul
437 const_tens = (set(mul.inputs) - {shared_in}).pop()
438 # check that it is a scalar
439 if const_tens.shape != []:
440 return op
441 const = const_tens.ops[0]
442 # check that it is a constant
443 if const.type != "Const":
444 return op
445 else:
446 return op
447
448 val = const.outputs[0].values
449 if val >= 0:
450 new_op = "LeakyRelu"
451 op.attrs["alpha"] = val
452 elif val == -1:
453 new_op = "Abs"
454 else:
455 return op
456
457 op.type = op.type.replace("Maximum", new_op)
458 op.name = op.name.replace("Maximum", new_op)
459 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op)
460 op.inputs = [shared_in]
461 return op
462
463
464def supported_operator_check(op, arch):
465 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
466 return op
467
468
469def optimise_graph_a(nng, arch, verbose_graph=False):
470 if verbose_graph:
471 nng.print_graph()
472
473 op_rewrite_list = [
474 # mark block type and check if the operations are supported
475 mark_npu_block_type,
476 supported_operator_check,
477 # then do any rewrites of supported operators
478 convert_depthwise_to_conv,
479 fixup_fully_connected_input,
480 fixup_pack_input,
481 fixup_conv2d_backprop,
482 fixup_act_reorder,
483 add_padding_fields,
484 mark_npu_block_type,
485 # convert_mul_max_to_abs_or_lrelu # TODO: enable optimisation once quantisation issues are resolved
486 ]
487
488 for idx, sg in enumerate(nng.subgraphs):
489 # rewrite graph pass
490 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Diego Russoea6111a2020-04-14 18:41:58 +0100491 sg, arch, [fixup_unpack_output], op_rewrite_list, rewrite_unsupported=False
Tim Hall79d07d22020-04-27 18:20:16 +0100492 )
493
494 for idx, sg in enumerate(nng.subgraphs):
495 # remove passthrough tensors
Diego Russoea6111a2020-04-14 18:41:58 +0100496 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [remove_passthrough_tensor], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100497
498 if verbose_graph:
499 nng.print_graph()
500 return nng
501
Diego Russoea6111a2020-04-14 18:41:58 +0100502
Tim Hall79d07d22020-04-27 18:20:16 +0100503def optimise_graph_b(nng, arch, verbose_graph=False):
504 if verbose_graph:
505 nng.print_graph()
506
507 for idx, sg in enumerate(nng.subgraphs):
508 # combined rewrite graph pass
Diego Russoea6111a2020-04-14 18:41:58 +0100509 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [rewrite_concat, rewrite_split], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100510
511 if verbose_graph:
512 nng.print_graph()
513 return nng