blob: 78c0dcd40a9d272310396a58f8061fda4ed5f8fa [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
Fredrik Svedberga0c36242020-06-03 15:43:31 +020030from .softmax import SoftMax
Michael McGeaghc5b549b2020-08-07 11:54:28 +010031from .tensor import create_const_tensor
32from .tensor import create_reshape_tensor
Charles Xu9a03fdf2020-07-02 15:12:40 +020033from .tensor import QuantizationParameters
Diego Russoe8a10452020-04-21 17:39:10 +010034from .tensor import Tensor
Tim Hall79d07d22020-04-27 18:20:16 +010035
36passthrough_nodes = set(("Identity",))
37
38
39def remove_passthrough_tensor(tens, arch):
40 if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes:
41 assert len(tens.ops[0].inputs) == 1
42 tens = tens.ops[0].inputs[0]
43 return tens
44
45
46def rewrite_concat(tens, arch):
47 if len(tens.ops) == 1 and tens.ops[0].is_concat_op():
48 concat_op = tens.ops[0]
49 if tens != concat_op.outputs[0]:
50 return tens # don't attempt to rewrite the min/max outputs of QuantizedConcat
51
52 # Not supported so leave it and run on CPU
53 if not concat_op.run_on_npu:
54 return tens
55
56 inputs, axis = concat_op.get_concat_inputs_axis()
57
58 tens.ops = []
59 offset = 0
60 for idx, inp in enumerate(inputs):
61 new_op = Operation("ConcatSliceWrite", concat_op.name + str(idx))
62 new_op.inputs = [inp]
63 new_op.outputs = [tens]
64 new_op.attrs["concat_axis"] = axis
65 new_op.attrs["concat_start"] = offset
66 offset += inp.shape[axis]
67 new_op.attrs["concat_end"] = offset
68 new_op.run_on_npu = True
69 tens.ops.append(new_op)
70 assert tens.shape[axis] == offset
71
Patrik Gustavsson29d568e2020-08-18 10:11:21 +020072 # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a
73 # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte
74 # aligned. For other values of axis the address offsets will be 16 byte aligned, as they are all based on c = 0
Patrik Gustavsson458a2082020-08-13 13:41:05 +020075 # and those addresses are always 16 byte aligned due to the NHCWB16 format.
Patrik Gustavsson29d568e2020-08-18 10:11:21 +020076 if axis == (len(tens.shape) - 1):
Patrik Gustavsson458a2082020-08-13 13:41:05 +020077 for op in tens.ops:
78 if op.attrs["concat_start"] % 16 != 0:
79 tens.avoid_NHCWB16 = True
80 break
81
Tim Hall79d07d22020-04-27 18:20:16 +010082 return tens
83
84
85def rewrite_split(tens, arch):
86
87 if len(tens.ops) == 1 and tens.ops[0].is_split_op():
88 split_op = tens.ops[0]
89
90 # Not supported so leave it and run on CPU
91 if not split_op.run_on_npu:
92 return tens
93
94 inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis()
95
96 tens.ops = []
97 new_op = Operation("SplitSliceRead", split_op.name)
98 new_op.inputs = [inp]
Tim Hall79d07d22020-04-27 18:20:16 +010099
100 # For Split the offset cannot be extracted from the tensor so it has to
101 # be calculated from the index of the output tensor
Diego Russoea6111a2020-04-14 18:41:58 +0100102 if axis is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100103 # Get the start and end of the split
104 offset_start = [0] * len(tens.shape)
105 offset_end = [0] * len(tens.shape)
106 for out in outputs:
107 if out == tens:
108 break
109 offset_start[axis] += out.shape[axis]
110
Patrik Gustavssoneebb1c22020-08-18 15:03:04 +0200111 # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input
112 if (offset_start[-1] % 16) != 0:
113 inp.avoid_NHCWB16 = True
114
Tim Hall79d07d22020-04-27 18:20:16 +0100115 offset_end[axis] = offset_start[axis] + tens.shape[axis]
116
117 new_op.attrs["split_start"] = offset_start
118 new_op.attrs["split_end"] = offset_end
119 new_op.run_on_npu = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100120 new_op.set_output_tensor(tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100121
122 return tens
123
124
125def needed_total_padding(input_size, stride, filter_size):
126 out_size = (input_size + stride - 1) // stride
127 needed_input = (out_size - 1) * stride + filter_size
128 total_padding = max(0, needed_input - input_size)
129 return total_padding
130
131
132def calc_padding_and_skirt(padding_type, kernel_size, stride, input_dims):
133 ypad = needed_total_padding(int(input_dims[1]), int(stride[1]), int(kernel_size[0]))
134 xpad = needed_total_padding(int(input_dims[2]), int(stride[2]), int(kernel_size[1]))
135 if padding_type == b"SAME":
136 left_pad = (xpad + 0) // 2
137 right_pad = (xpad + 1) // 2
138 top_pad = (ypad + 0) // 2
139 bottom_pad = (ypad + 1) // 2
140 elif padding_type == b"VALID":
141 left_pad = 0
142 right_pad = 0
143 top_pad = 0
144 bottom_pad = 0
145 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200146 raise UnsupportedFeatureError("Unknown padding {}".format(str(padding_type)))
Tim Hall79d07d22020-04-27 18:20:16 +0100147 padding = (top_pad, left_pad, bottom_pad, right_pad)
148 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
149 return padding, skirt
150
Tim Hallc30f4952020-06-15 20:47:35 +0100151
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200152def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_dims, upscaling_factor):
153 kernel_height, kernel_width = kernel_size[0], kernel_size[1]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200154 if padding_type == b"SAME":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200155 ypad = needed_total_padding(int(input_dims[1]) * upscaling_factor, int(stride[1]), int(kernel_height))
156 xpad = needed_total_padding(int(input_dims[2]) * upscaling_factor, int(stride[2]), int(kernel_width))
157
158 right_pad = ((xpad + 1) // upscaling_factor) - 1
159 bottom_pad = ((ypad + 1) // upscaling_factor) - 1
160 left_pad = max(kernel_width - 1 - right_pad, 0)
161 top_pad = max(kernel_height - 1 - bottom_pad, 0)
162
Jacob Bohlincf7da102020-05-20 09:03:40 +0200163 elif padding_type == b"VALID":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200164 right_pad = max(kernel_width - 2, 0)
165 bottom_pad = max(kernel_height - 2, 0)
166 left_pad = kernel_width - 1
167 top_pad = kernel_height - 1
Jacob Bohlincf7da102020-05-20 09:03:40 +0200168 else:
169 assert 0, "Unknown padding"
170
171 padding = (top_pad, left_pad, bottom_pad, right_pad)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200172 skirt = padding
Jacob Bohlincf7da102020-05-20 09:03:40 +0200173 return padding, skirt
174
Tim Hall79d07d22020-04-27 18:20:16 +0100175
176def fixup_conv2d_backprop(op, arch):
177 if op.type == "Conv2DBackpropInput":
178 # flip the inputs
179 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200180 op.type = "Conv2DBackpropInputSwitchedBias"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200181
182 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100183 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100184
185 return op
186
187
Charles Xu9a03fdf2020-07-02 15:12:40 +0200188# Convert the op to an elementwise add
189def convert_resizebilinear_1x1_to_add(op):
190 op.type = "AddAct"
191 op.name = op.name + "_add"
192 op.attrs.update({"npu_block_type": NpuBlockType.ElementWise})
193 op.attrs["resizebilinear"] = True
194 # Create an input tensor filled with zeros
195 shape = op.outputs[0].shape
196 tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add")
197 tens.values = np.zeros(shape)
198 tens.quant_values = np.zeros(shape, np.uint8)
199 tens.quantization = QuantizationParameters(0.0, 255.0)
200 tens.quantization.scale_f32 = 1.0
201 tens.quantization.zero_point = 0
202 tens.consumer_list = [op]
203 tens_op = op.inputs[1].ops[0]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100204 tens_op.set_output_tensor(tens)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200205 # Set the add inputs
206 op.inputs[1] = op.inputs[0]
207 op.inputs[0] = tens
208
209 return op
210
211
212def fixup_resizebilinear(op, arch):
213 if op.type == "ResizeBilinear":
214 if op.inputs[0].shape[1] == 1 and op.inputs[0].shape[2] == 1:
215 convert_resizebilinear_1x1_to_add(op)
Charles Xu36ffaf32020-08-05 15:40:44 +0200216 elif op.inputs[0].shape == op.outputs[0].shape:
217 # Bypass nop resizebilinear
218 op.inputs = op.inputs[:1]
219 op.type = "Identity"
Charles Xu9a03fdf2020-07-02 15:12:40 +0200220
221 return op
222
223
Tim Hall79d07d22020-04-27 18:20:16 +0100224def fixup_fully_connected_input(op, arch):
225 if op.type == "FullyConnectedAct":
226 inp = op.inputs[0]
227 weights = op.inputs[1]
228
229 n_in_elems = weights.shape[-2]
230 elms = inp.elements()
231 batch_size = elms // n_in_elems
232 assert batch_size * n_in_elems == elms
233
234 desired_shape = [batch_size, n_in_elems]
235 if inp.shape != desired_shape:
236 # mismatch, insert a reshape to fix this.
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100237 op.inputs[0] = create_reshape_tensor(inp, desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100238
239 return op
240
241
242def fixup_pack_input(op, arch):
243 if op.type == "Pack":
244 # Pack is also referred to as Stack
245 # Requires the rewrite_concat function to be called on the op afterwards
246 axis = int(op.attrs["axis"])
247 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
248
249 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100250 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100251
252 for idx, inp in enumerate(op.inputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100253 reshape_out = inp.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100254 reshape_out.set_all_shapes(desired_shape)
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100255
256 reshape_op = Operation("Reshape", "{}{}_reshape".format(op.name, idx))
257 reshape_op.attrs["new_shape"] = desired_shape
258 reshape_op.inputs = [inp, new_shape_tens]
259 reshape_op.set_output_tensor(reshape_out)
Tim Hall79d07d22020-04-27 18:20:16 +0100260
261 op.inputs[idx] = reshape_out
262
263 op.type = "PackReshaped"
264
265 return op
266
267
268def fixup_unpack_output(tens, arch):
269 op = tens.ops[0]
270 if op.type in set(("Unpack", "StridedSlice")):
271 # Unpack is also referred to as Unstack
272 # Requires the rewrite_split function to be called on the op afterwards
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200273
274 reshape_input_shape = tens.shape
Tim Hall79d07d22020-04-27 18:20:16 +0100275 if op.type == "StridedSlice":
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200276 new_axis_mask = op.attrs["new_axis_mask"]
Tim Hall79d07d22020-04-27 18:20:16 +0100277 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Louis Verhaard7db78962020-05-25 15:05:26 +0200278 ellipsis_mask = op.attrs["ellipsis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200279
280 if (new_axis_mask != 0 and shrink_axis_mask != 0) or ellipsis_mask != 0:
281 # Not supported, will be put on CPU
282 return tens
283 if shrink_axis_mask == 0 and new_axis_mask == 0:
Tim Hall79d07d22020-04-27 18:20:16 +0100284 # Equal Rank StridedSlice, no need to insert reshape
285 return tens
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200286 elif shrink_axis_mask != 0:
287 n = 0
288 axis = 0
289 while shrink_axis_mask:
290 prev_mask = shrink_axis_mask
291 n += 1
292 shrink_axis_mask &= shrink_axis_mask - 1
293 axis = int(math.log2(prev_mask - shrink_axis_mask))
294 reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100295
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200296 assert len(tens.shape) == (len(op.inputs[0].shape) - n)
297 op.attrs["shrink_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100298
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200299 elif new_axis_mask != 0:
300 n = 0
301 axis = 0
302 while new_axis_mask:
303 prev_mask = new_axis_mask
304 n += 1
305 new_axis_mask &= new_axis_mask - 1
306 axis = int(math.log2(prev_mask - new_axis_mask))
Louis Verhaard7db78962020-05-25 15:05:26 +0200307 reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1) :]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200308 new_axis_mask >>= 1
309
310 assert len(tens.shape) == (len(op.inputs[0].shape) + n)
311 op.attrs["new_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100312 else:
313 axis = int(op.attrs["axis"])
314 op.type = "UnpackReshaped"
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200315 reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100316
317 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100318 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, tens.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100319
320 for idx, out_tens in enumerate(op.outputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100321 reshape_in = out_tens.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100322 reshape_in.set_all_shapes(reshape_input_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100323 reshape_in.ops = [op]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100324
325 reshape_op = Operation("Reshape", "{}{}_reshape".format(op.name, idx))
326 reshape_op.attrs["new_shape"] = reshape_input_shape
Tim Hall79d07d22020-04-27 18:20:16 +0100327 reshape_op.inputs = [reshape_in, new_shape_tens]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100328 reshape_op.set_output_tensor(out_tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100329
330 op.outputs[idx] = reshape_in
331
332 return tens
333
334
335def add_padding_fields(op, arch):
336 if "padding" in op.attrs:
337 if "Conv" in op.type:
338 kernel_size = op.inputs[1].shape[:2]
339 input_shape = op.inputs[0].shape
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200340 elif "Pool" in op.type or op.type in ("ResizeBilinear", "ReduceSum"):
Tim Hall79d07d22020-04-27 18:20:16 +0100341 kernel_size = op.attrs["ksize"][1:3]
342 input_shape = op.inputs[0].shape
343 elif op.type == "ExtractImagePatches":
344 kernel_size = op.attrs["ksizes"][1:3]
345 input_shape = op.inputs[0].shape
346 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200347 raise UnsupportedFeatureError("Unknown operation that uses padding: {}".format(op.type))
Tim Hall79d07d22020-04-27 18:20:16 +0100348
Jacob Bohlincf7da102020-05-20 09:03:40 +0200349 if op.type == "Conv2DBackpropInputSwitchedBias":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200350 upscaling_factor = op.outputs[0].shape[1] // input_shape[1]
Tim Hallc30f4952020-06-15 20:47:35 +0100351 padding, skirt = calc_upscaled_padding_and_skirt(
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200352 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
Tim Hallc30f4952020-06-15 20:47:35 +0100353 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200354 else:
355 dilation_h, dilation_w = op.get_dilation_h_w()
356 dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1]
Tim Hallc30f4952020-06-15 20:47:35 +0100357 padding, skirt = calc_padding_and_skirt(
358 op.attrs["padding"], dilated_kernel_size, op.attrs["strides"], input_shape
359 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200360
Tim Hall79d07d22020-04-27 18:20:16 +0100361 op.attrs["explicit_padding"] = padding
362 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200363
Tim Hall79d07d22020-04-27 18:20:16 +0100364 return op
365
366
Jacob Bohlincf7da102020-05-20 09:03:40 +0200367conv_op = set(("Conv2D", "QuantizedConv2D", "Conv2DBackpropInputSwitchedBias", "Conv2DBiasAct"))
Tim Hall79d07d22020-04-27 18:20:16 +0100368fc_op = set(
369 (
370 "MatMul",
371 "QuantizedMatMul",
372 "BlockLSTM",
373 "RnnAct",
374 "UnidirectionalSequenceRnnAct",
375 "BidirectionalSequenceRnnAct",
376 "LstmAct",
377 "UnidirectionalSequenceLstmAct",
378 "BidirectionalSequenceLstmAct",
379 "FullyConnectedAct",
380 )
381)
382depthwise_op = set(("DepthwiseConv2dNative", "DepthwiseConv2dBiasAct",))
Louis Verhaard7db78962020-05-25 15:05:26 +0200383pool_op = set(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200384 ("AvgPool", "MaxPool", "QuantizedAvgPool", "QuantizedMaxPool", "AvgPoolAct", "MaxPoolAct", "ResizeBilinear")
Louis Verhaard7db78962020-05-25 15:05:26 +0200385)
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200386reduce_sum_ops = set(("ReduceSum",))
387elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum", "LeakyRelu", "Abs", "CLZ", "SHL", "SHR"))
Charles Xu78792222020-05-13 10:15:26 +0200388binary_elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum"))
Tim Hall79d07d22020-04-27 18:20:16 +0100389activation_ops = set(("Relu", "Relu6", "ReluN1To1", "Sigmoid", "Tanh"))
390memory_only_ops = set(("Reshape",))
391
Diego Russoea6111a2020-04-14 18:41:58 +0100392
Tim Hall79d07d22020-04-27 18:20:16 +0100393# Check if the op can be reordered
394def get_prepend_op(op):
395 inp = op.inputs[0]
396 # The op should be reordered between prev_op and prep_op
397 prev_op = inp.ops[-1]
398 prep_op = None
399 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
400 prep_op = prev_op
401 inp = prev_op.inputs[0]
402 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100403 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 +0100404 return prep_op
405
406 return None
407
408
409def mark_npu_block_type(op, arch):
410 npu_block_type = NpuBlockType.Default
411 if op.type in conv_op:
412 npu_block_type = NpuBlockType.ConvolutionMxN
413 elif op.type in fc_op:
414 npu_block_type = NpuBlockType.VectorProduct
415 elif op.type in depthwise_op:
416 npu_block_type = NpuBlockType.ConvolutionDepthWise
417 elif op.type in pool_op:
418 npu_block_type = NpuBlockType.Pooling
419 elif op.type in elementwise_op:
420 npu_block_type = NpuBlockType.ElementWise
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200421 elif op.type in reduce_sum_ops:
422 npu_block_type = NpuBlockType.ReduceSum
Tim Hall79d07d22020-04-27 18:20:16 +0100423
424 op.attrs["npu_block_type"] = npu_block_type
425 return op
426
427
428def convert_depthwise_to_conv(op, arch):
429 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
430 # the ofm depth equals the depth multipler.
431 # If those conditions are true, then we can perform a simple
432 # switch of the operator type (and weight order)
433
434 if ("DepthwiseConv2d" in op.type) and (op.attrs["depth_multiplier"] != 1):
435 ifm_tensor = op.inputs[0]
436 weight_tensor = op.inputs[1]
437 ofm_tensor = op.outputs[0]
438 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
439 # Change op type to Conv2d
440 op.type = op.type.replace("DepthwiseConv2d", "Conv2D")
441 del op.attrs["channel_multiplier"]
442 del op.attrs["depth_multiplier"]
443
444 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100445 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100446 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200447 raise UnsupportedFeatureError(
448 "Unsupported DepthwiseConv2d with depth_multiplier = {}, ifm channels = {}, ofm channels = {}".format(
Tim Hall79d07d22020-04-27 18:20:16 +0100449 op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3]
450 )
451 )
Tim Hall79d07d22020-04-27 18:20:16 +0100452 return op
453
454
Jacob Bohline843d332020-06-23 12:12:56 +0200455def reorder_depthwise_weights(op, arch):
456 if "DepthwiseConv2d" in op.type:
457 weight_tensor = op.inputs[1]
458 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100459 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200460 weight_tensor.weight_transpose_depthwise = True
461
462 return op
463
464
Michael McGeagh8d939c02020-07-29 13:11:43 +0100465def convert_conv_to_fc(op, arch):
466 # Conv 1x1 can be equivalent to Fully Connected.
467 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
468 # caching/double buffering for the weights.
469 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
470 if op.type == "Conv2DBiasAct":
471 _, h, w, _ = op.inputs[0].shape
472 kh, kw, _, _ = op.inputs[1].shape
473 if h == 1 and w == 1 and kh == 1 and kw == 1:
474 # Overwrite this op as a Fully Connected Op
475 op.name += "_fc"
476 op.type = "FullyConnectedAct"
477 faf = op.attrs.get("fused_activation_function", None)
478 op.attrs = {
479 "fused_activation_function": faf,
480 "weights_format": 0,
481 "npu_block_type": NpuBlockType.VectorProduct,
482 }
483 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
484 weight_tensor = op.inputs[1]
485 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
486 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
487 # The output from a fully connected is expected to be 2D so we need to add a reshape layer to convert it
488 # back to 4D afterwards as the next layer is expecting that shape
489 orig_ofm_tensor = op.outputs[0]
490 # Reshape this ops output to be 2D: {(N*H*W), C} (We know N H and W are all 1 so this becomes {1, C})
491 fc_ofm_tensor = orig_ofm_tensor.clone("_fc")
492 fc_ofm_tensor.set_all_shapes([1, fc_ofm_tensor.shape[-1]])
493 fc_ofm_tensor.ops = [op]
494 # Add a reshape after the new OFM to convert it back to the original 4D shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100495 reshape_name = op.name + "_reshape"
496 new_shape_tens = create_const_tensor(reshape_name + "_shape", [1], DataType.int32, orig_ofm_tensor.shape)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100497 reshape_op = Operation("Reshape", reshape_name)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100498 reshape_op.attrs["new_shape"] = orig_ofm_tensor.shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100499 reshape_op.inputs = [fc_ofm_tensor, new_shape_tens]
500 reshape_op.set_output_tensor(orig_ofm_tensor)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100501 # Replace this ops OFM to point to the 2D tensor
502 op.outputs[0] = fc_ofm_tensor
503 return op
504
505
Tim Hall79d07d22020-04-27 18:20:16 +0100506# Reorder activation op if it's after the memory only operations
507def fixup_act_reorder(op, arch):
508 if op.type in activation_ops:
509 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100510 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100511 act_op = op.clone("_reordered")
512 act_op.inputs = [prep_op.inputs[0]]
513 act_op_out = act_op.inputs[0].clone("_acted")
514 act_op_out.quantization = op.outputs[0].quantization.clone()
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100515 act_op.set_output_tensor(act_op_out)
Tim Hall79d07d22020-04-27 18:20:16 +0100516 prep_op.inputs[0] = act_op_out
517 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
518
519 # Mark the op so that it will be removed as passthrough later on
520 op.type = "Identity"
521 return op
522
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200523
Charles Xu78792222020-05-13 10:15:26 +0200524def fixup_elementwise_with_scalars(op, arch):
525 if op.type in binary_elementwise_op:
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200526 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200527 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
528 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
529 if diff > 0:
530 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
531 elif diff < 0:
532 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200533 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
534 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
535 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
536 ifm_tensor.storage_shape = ifm_tensor.shape
537 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
538 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
539 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
540 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200541 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100542
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200543
Tim Hall4e127762020-05-15 16:05:49 +0100544# Set input/output tensor equivalence to the same id for memory operations
545def set_tensor_equivalence(op, arch):
546 if op.type == "Reshape":
547 eid = op.outputs[0].equivalence_id
548 for inp in op.inputs:
549 inp.equivalence_id = eid
550 return op
551
552
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200553def convert_softmax(op, arch):
554 if op.type == "Softmax" and op.run_on_npu:
555 softmax = SoftMax(op)
556 op = softmax.get_graph()
557 return op
558
559
Tim Hall79d07d22020-04-27 18:20:16 +0100560def convert_mul_max_to_abs_or_lrelu(op, arch):
Diego Russoea6111a2020-04-14 18:41:58 +0100561 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100562
563 Input X For X = -1 or X > 0
564 | \ / This subgraph can be replaced with either
565 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
566 | /
567 Max
568 """
569
570 if op.type == "Maximum":
571 # finds the Mul input(s) to the Max
572 muls = [i for i in op.inputs if i.ops[0].type == "MulAct"]
573 if len(muls) == 1:
574 mul = muls[0].ops[0]
575 elif len(muls) == 2:
576 # In the case both inputs are Muls, find the one with the same input as the Max
577 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
578 else:
579 # No Mul inputs
580 return op
581
582 # make sure the Mul doesn't have any other consumers
583 if len(mul.outputs[0].consumers()) != 1:
584 return op
585 # make sure the Mul doesn't have a faf
586 if mul.attrs["fused_activation_function"]:
587 return op
588
589 # finds the branched input that goes to both the Max and the Mul
590 shared = set(op.inputs) & set(mul.inputs)
591 if len(shared) == 1:
592 shared_in = shared.pop()
593 # find the constant scalar input to the Mul
594 const_tens = (set(mul.inputs) - {shared_in}).pop()
595 # check that it is a scalar
596 if const_tens.shape != []:
597 return op
598 const = const_tens.ops[0]
599 # check that it is a constant
600 if const.type != "Const":
601 return op
602 else:
603 return op
604
605 val = const.outputs[0].values
606 if val >= 0:
607 new_op = "LeakyRelu"
608 op.attrs["alpha"] = val
609 elif val == -1:
610 new_op = "Abs"
611 else:
612 return op
613
614 op.type = op.type.replace("Maximum", new_op)
615 op.name = op.name.replace("Maximum", new_op)
616 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op)
617 op.inputs = [shared_in]
618 return op
619
620
Dwight Lidman42fed942020-05-29 09:37:03 +0200621def add_attrs_to_resizebilinear(op, arch):
Tim Hallc30f4952020-06-15 20:47:35 +0100622 if op.type == "ResizeBilinear" and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +0200623 input_tensor = op.inputs[0]
624 upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2]
625 out_shape = op.outputs[0].shape[1:3]
626 if not op.attrs["align_corners"] and out_shape == upscaled_shape:
627 # this means the output is supposed to be a x2 upscale,
628 # so we need to do SAME padding
629 op.attrs["padding"] = b"SAME"
630 elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]:
631 # here we can just run the avg pool without padding and
632 # produce a (M * 2 - 1, N * 2 - 1) sized output
633 op.attrs["padding"] = b"VALID"
634 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +0200635 return op
Dwight Lidman42fed942020-05-29 09:37:03 +0200636 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +0100637 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +0200638 return op
639
640
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200641def add_bias_tensor(op, arch):
642 if ("Conv2d" in op.type or op.type.startswith("FullyConnected")) and not op.inputs[-1]:
643 # Add bias/scale tensor filled with zeros
644 weight_shape = op.inputs[1].shape
645 weight_sets = weight_shape[-1]
646 bias_values = [0] * weight_sets
647 scale_tens = create_const_tensor(op.name + "_bias", [weight_sets], DataType.int32, bias_values)
648 op.set_input_tensor(scale_tens, -1)
649
650 return op
651
652
Tim Hall79d07d22020-04-27 18:20:16 +0100653def supported_operator_check(op, arch):
654 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
655 return op
656
657
658def optimise_graph_a(nng, arch, verbose_graph=False):
659 if verbose_graph:
660 nng.print_graph()
661
662 op_rewrite_list = [
663 # mark block type and check if the operations are supported
664 mark_npu_block_type,
Tim Hall4e127762020-05-15 16:05:49 +0100665 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +0100666 supported_operator_check,
667 # then do any rewrites of supported operators
668 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +0100669 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200670 convert_softmax,
Tim Hall79d07d22020-04-27 18:20:16 +0100671 fixup_fully_connected_input,
672 fixup_pack_input,
673 fixup_conv2d_backprop,
674 fixup_act_reorder,
Dwight Lidman42fed942020-05-29 09:37:03 +0200675 add_attrs_to_resizebilinear,
Tim Hall79d07d22020-04-27 18:20:16 +0100676 add_padding_fields,
677 mark_npu_block_type,
Charles Xu78792222020-05-13 10:15:26 +0200678 fixup_elementwise_with_scalars,
Jacob Bohline843d332020-06-23 12:12:56 +0200679 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +0200680 fixup_resizebilinear,
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200681 add_bias_tensor,
Tim Hall79d07d22020-04-27 18:20:16 +0100682 # convert_mul_max_to_abs_or_lrelu # TODO: enable optimisation once quantisation issues are resolved
683 ]
684
685 for idx, sg in enumerate(nng.subgraphs):
686 # rewrite graph pass
687 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Diego Russoea6111a2020-04-14 18:41:58 +0100688 sg, arch, [fixup_unpack_output], op_rewrite_list, rewrite_unsupported=False
Tim Hall79d07d22020-04-27 18:20:16 +0100689 )
690
691 for idx, sg in enumerate(nng.subgraphs):
692 # remove passthrough tensors
Diego Russoea6111a2020-04-14 18:41:58 +0100693 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [remove_passthrough_tensor], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100694
695 if verbose_graph:
696 nng.print_graph()
697 return nng
698
Diego Russoea6111a2020-04-14 18:41:58 +0100699
Tim Hall79d07d22020-04-27 18:20:16 +0100700def optimise_graph_b(nng, arch, verbose_graph=False):
701 if verbose_graph:
702 nng.print_graph()
703
704 for idx, sg in enumerate(nng.subgraphs):
705 # combined rewrite graph pass
Diego Russoea6111a2020-04-14 18:41:58 +0100706 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [rewrite_concat, rewrite_split], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100707
708 if verbose_graph:
709 nng.print_graph()
710 return nng