blob: b29a3823384225ef6ef064a65e5100951e56e4f1 [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.
16
17
18# Description:
19# Early optimisation of the network graph, using the rewrite_graph module to do the traversal of the graph. These are
20# split into two parts optimise_graph_a and optimise_graph_b.
21
Tim Hall79d07d22020-04-27 18:20:16 +010022import math
Diego Russoea6111a2020-04-14 18:41:58 +010023
24import numpy as np
25
26from . import rewrite_graph
27from .operation import Operation, NpuBlockType
28from .tensor import Tensor
29from .data_type import DataType
30
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:
129 assert 0, "Unknown padding"
130 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"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200219 ellipsis_mask = op.attrs["ellipsis_mask"]
220
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))
248 reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1):]
249 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
286 elif "Pool" in op.type:
287 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:
293 assert 0, "Unknown operation that uses padding"
294
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",))
317pool_op = set(("AvgPool", "MaxPool", "QuantizedAvgPool", "QuantizedMaxPool", "AvgPoolAct", "MaxPoolAct"))
318elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum", "LeakyRelu", "Abs"))
319activation_ops = set(("Relu", "Relu6", "ReluN1To1", "Sigmoid", "Tanh"))
320memory_only_ops = set(("Reshape",))
321
Diego Russoea6111a2020-04-14 18:41:58 +0100322
Tim Hall79d07d22020-04-27 18:20:16 +0100323# Check if the op can be reordered
324def get_prepend_op(op):
325 inp = op.inputs[0]
326 # The op should be reordered between prev_op and prep_op
327 prev_op = inp.ops[-1]
328 prep_op = None
329 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
330 prep_op = prev_op
331 inp = prev_op.inputs[0]
332 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100333 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 +0100334 return prep_op
335
336 return None
337
338
339def mark_npu_block_type(op, arch):
340 npu_block_type = NpuBlockType.Default
341 if op.type in conv_op:
342 npu_block_type = NpuBlockType.ConvolutionMxN
343 elif op.type in fc_op:
344 npu_block_type = NpuBlockType.VectorProduct
345 elif op.type in depthwise_op:
346 npu_block_type = NpuBlockType.ConvolutionDepthWise
347 elif op.type in pool_op:
348 npu_block_type = NpuBlockType.Pooling
349 elif op.type in elementwise_op:
350 npu_block_type = NpuBlockType.ElementWise
351
352 op.attrs["npu_block_type"] = npu_block_type
353 return op
354
355
356def convert_depthwise_to_conv(op, arch):
357 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
358 # the ofm depth equals the depth multipler.
359 # If those conditions are true, then we can perform a simple
360 # switch of the operator type (and weight order)
361
362 if ("DepthwiseConv2d" in op.type) and (op.attrs["depth_multiplier"] != 1):
363 ifm_tensor = op.inputs[0]
364 weight_tensor = op.inputs[1]
365 ofm_tensor = op.outputs[0]
366 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
367 # Change op type to Conv2d
368 op.type = op.type.replace("DepthwiseConv2d", "Conv2D")
369 del op.attrs["channel_multiplier"]
370 del op.attrs["depth_multiplier"]
371
372 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
373 weight_tensor.shape = weight_tensor.storage_shape = weight_tensor.bandwidth_shape = list(
374 weight_tensor.quant_values.shape
375 )
376 else:
377 print(
378 "Error: Unsupported DepthwiseConv2d with depth_multiplier = {0}, "
379 "ifm channels = {1}, ofm channels = {2}".format(
380 op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3]
381 )
382 )
383 assert False
384 return op
385
386
387# Reorder activation op if it's after the memory only operations
388def fixup_act_reorder(op, arch):
389 if op.type in activation_ops:
390 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100391 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100392 act_op = op.clone("_reordered")
393 act_op.inputs = [prep_op.inputs[0]]
394 act_op_out = act_op.inputs[0].clone("_acted")
395 act_op_out.quantization = op.outputs[0].quantization.clone()
396 act_op_out.ops = [act_op]
397 act_op.outputs = [act_op_out]
398 prep_op.inputs[0] = act_op_out
399 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
400
401 # Mark the op so that it will be removed as passthrough later on
402 op.type = "Identity"
403 return op
404
405
406def convert_mul_max_to_abs_or_lrelu(op, arch):
Diego Russoea6111a2020-04-14 18:41:58 +0100407 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100408
409 Input X For X = -1 or X > 0
410 | \ / This subgraph can be replaced with either
411 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
412 | /
413 Max
414 """
415
416 if op.type == "Maximum":
417 # finds the Mul input(s) to the Max
418 muls = [i for i in op.inputs if i.ops[0].type == "MulAct"]
419 if len(muls) == 1:
420 mul = muls[0].ops[0]
421 elif len(muls) == 2:
422 # In the case both inputs are Muls, find the one with the same input as the Max
423 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
424 else:
425 # No Mul inputs
426 return op
427
428 # make sure the Mul doesn't have any other consumers
429 if len(mul.outputs[0].consumers()) != 1:
430 return op
431 # make sure the Mul doesn't have a faf
432 if mul.attrs["fused_activation_function"]:
433 return op
434
435 # finds the branched input that goes to both the Max and the Mul
436 shared = set(op.inputs) & set(mul.inputs)
437 if len(shared) == 1:
438 shared_in = shared.pop()
439 # find the constant scalar input to the Mul
440 const_tens = (set(mul.inputs) - {shared_in}).pop()
441 # check that it is a scalar
442 if const_tens.shape != []:
443 return op
444 const = const_tens.ops[0]
445 # check that it is a constant
446 if const.type != "Const":
447 return op
448 else:
449 return op
450
451 val = const.outputs[0].values
452 if val >= 0:
453 new_op = "LeakyRelu"
454 op.attrs["alpha"] = val
455 elif val == -1:
456 new_op = "Abs"
457 else:
458 return op
459
460 op.type = op.type.replace("Maximum", new_op)
461 op.name = op.name.replace("Maximum", new_op)
462 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op)
463 op.inputs = [shared_in]
464 return op
465
466
467def supported_operator_check(op, arch):
468 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
469 return op
470
471
472def optimise_graph_a(nng, arch, verbose_graph=False):
473 if verbose_graph:
474 nng.print_graph()
475
476 op_rewrite_list = [
477 # mark block type and check if the operations are supported
478 mark_npu_block_type,
479 supported_operator_check,
480 # then do any rewrites of supported operators
481 convert_depthwise_to_conv,
482 fixup_fully_connected_input,
483 fixup_pack_input,
484 fixup_conv2d_backprop,
485 fixup_act_reorder,
486 add_padding_fields,
487 mark_npu_block_type,
488 # convert_mul_max_to_abs_or_lrelu # TODO: enable optimisation once quantisation issues are resolved
489 ]
490
491 for idx, sg in enumerate(nng.subgraphs):
492 # rewrite graph pass
493 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Diego Russoea6111a2020-04-14 18:41:58 +0100494 sg, arch, [fixup_unpack_output], op_rewrite_list, rewrite_unsupported=False
Tim Hall79d07d22020-04-27 18:20:16 +0100495 )
496
497 for idx, sg in enumerate(nng.subgraphs):
498 # remove passthrough tensors
Diego Russoea6111a2020-04-14 18:41:58 +0100499 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [remove_passthrough_tensor], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100500
501 if verbose_graph:
502 nng.print_graph()
503 return nng
504
Diego Russoea6111a2020-04-14 18:41:58 +0100505
Tim Hall79d07d22020-04-27 18:20:16 +0100506def optimise_graph_b(nng, arch, verbose_graph=False):
507 if verbose_graph:
508 nng.print_graph()
509
510 for idx, sg in enumerate(nng.subgraphs):
511 # combined rewrite graph pass
Diego Russoea6111a2020-04-14 18:41:58 +0100512 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [rewrite_concat, rewrite_split], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100513
514 if verbose_graph:
515 nng.print_graph()
516 return nng